2010-01-14 76 views
1

嗨,我是一个objC noob。我有一个问题用对象填充NSMutableArray。为什么我的数组保持为空?

for(id p in tmpArray){ 
    Person *person = [[Person alloc] init]; 
    person.usrName = p; 
    [persons addObject:person]; // after this line the persons 
           // array is still empty 
    [person release]; 
} 

人是属性NSMutableArray,问题是它是空的。这个人物的释放是否太早,或者我是否把它误解了?

+3

你如何检查你的数组是空的?你是如何初始化你的人员数组的? – Vladimir 2010-01-14 12:02:06

+0

用给定的信息只能猜测。我的猜测:这段代码是一个拥有'@property NSMutableArray * persons'的实例的一部分。 _Either_你不用* -init *初始化数组,或者你应该使用'self.persons'而不是'persons'。 – 2010-01-14 12:13:37

+0

我以为你不必初始化数组,如果你使它成为这样的属性? @property(nonatomic,retain)NSMutableArray * persons; – Oscar 2010-01-14 12:21:01

回答

2

需要初始化数组中的-init方法,这样才:

NSMutableArray *array = [[NSMutableArray alloc] init]; 
self.persons = array; // will be automatically retained 
         // because you're using the property 
[array release]; // we alloced - we release it 

不要忘记释放它:

-(void)dealloc { 
    self.persons = nil; // previous value of property 'persons' will be released 
    [super dealloc]; 
} 
+1

请补充一点,有些人使用'persons = [[NSMutableArray alloc] init]'和'[persons releases]'。这是因为访问者可能有副作用,因此不应该用于构建和解构。请参阅Mike Ash的博客进行讨论:http://www.mikeash.com/?page=pyblog/friday-qa-2009-11-27-using-accessors-in-init-and-dealloc.html这个'dealloc'方法是没有必要的,如果你的应用程序是垃圾收集。 (如果代码在非gc环境中使用,仍然不错) – 2010-01-14 12:50:01

+0

谢谢,@gs。我将代码更改为之前我也写过的内容 - 不知何故,我更喜欢显式的alloc/init/release而不是自动释放对象。 – 2010-01-14 13:40:15

+0

AdamWoś:这并不能解决你仍在'init'和'dealloc'中使用属性访问的问题。查看我对这个问题的评论,了解更多关于这是一个等待发生的错误的详细信息。 – 2010-01-16 06:14:47

2

确认您已经alloced和初始化数组您尝试的东西给它添加