2012-08-04 81 views
2

我試圖通過for循環將對象添加到NSMutableArray。但似乎每當我添加一個對象時,它將替換舊對象,以便我在該時間只有一個對象在數組中...addObject替換NSMutableArray中的前一個對象

您對什麼可能是錯誤有任何想法嗎?

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
LoginInfo *info = [[LoginInfo alloc] init]; 
info.startPost = @"0"; 
info.numberOfPosts = @"10"; 
info.postType = @"1"; 
getResults = [backendService getAllPosts:info]; 

for (NSInteger i = 0; i < [getResults count]; i++) { 

    Post *postInfo = [[Post alloc] init]; 
    postInfo = [getResults objectAtIndex:i]; 

    dataArray = [[NSMutableArray alloc] init]; 
    [dataArray addObject:postInfo.noteText]; 
    NSLog(@"RESULT TEST %@", dataArray); 

} 
} 

這是結果測試日誌,總是隻顯示輸出中最後添加的字符串。

回答

10

你初始化dataArray的內部進行循環,所以每次它再次創建(這意味着有沒有對象)和一個新的對象是在爲前加入

移動

dataArray = [[NSMutableArray alloc] init]; 

到環

也沒有必要對分配/初始化的postInfo對象時立即與來自getResults陣列的對象重寫它

+0

啊,感覺挺傻的,現在... :(感謝您的幫助的人! – Tom 2012-08-04 12:54:27

4

你保持重新初始化數組這一行循環的每次運行:

dataArray = [[NSMutableArray alloc] init]; 

所以dataArray被設置爲一個新的(空)數組循環的每次運行。

而是在循環之前初始化數組。嘗試是這樣的:

dataArray = [[NSMutableArray alloc] init]; 

for (NSInteger i = 0; i < [getResults count]; i++) { 

    PostInfo *postInfo = [getResults objectAtIndex:i]; 

    [dataArray addObject:postInfo.noteText]; 

    NSLog(@"RESULT TEST %@", dataArray); 

} 
相關問題