为什么我的阵列保持空?

时间:2010-01-14 11:55:48

标签: objective-c cocoa

嗨,我是一个objC菜鸟。我在使用对象填充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];
}

Persons是一个属性NSMutableArray,问题是它是空的。它过早发布了人物对象还是我错误地解释了它?

2 个答案:

答案 0 :(得分:2)

确保在尝试向其添加内容之前分配并初始化数组

答案 1 :(得分: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];
}