2010-01-14 39 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和初始化數組您嘗試的東西給它添加