我正在尝试将 UIButton 对象添加到数组中,但他们没有这样做。每当我调用 [pixels count] 或 [colors count] 时,它都会返回 0。我尝试使用 [self.arrayName addObject:myObject] 和 [arrayName addObject:myObject] 但似乎都不起作用。我是 Objective-C 的新手,所以它对我来说可能看起来很愚蠢,但这已经困扰了我一个多小时。
这是 ViewController.h 的代码
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
NSMutableArray *pixels;
NSMutableArray *colors;
}
@property (nonatomic, retain) NSMutableArray *pixels;
@property (nonatomic, retain) NSMutableArray *colors;
@end
这是ViewController.m中的相关代码
int x = 30;
int y = 60;
for(int i=0; i<10; i++ ) {
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
[self.pixels addObject:button];
x += 20;
y += 20;
}
我已经压缩了整个项目,可以在这里下载: http://mdl.fm/pixelated.zip
在此先感谢任何可以提供帮助的人!
最佳答案
在尝试使用数组之前尝试添加:
NSMutableArray *pixels = [[NSMutableArray alloc] init];
Obj-C 中的数组在使用前需要进行初始化。由于在 Obj-C 中调用 nil 实例上的方法只会返回零,因此很容易做到这一点,并且直到您的数组没有存储您认为应该存储的内容时才会注意到。
编辑以从评论中添加信息:
您可以将初始化放入 -ViewDidLoad
方法中,这样一旦 ViewController
本身就绪,它们就可以开始了。确保您保留
它们,这样它们就不会自动被垃圾回收。
关于objective-c - 无法让 addObject 在 NSMutableArray 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13713446/