2015-11-02 62 views
0

我有一個公司的數組的JSON響應。 然後我遍歷數組,以便將它們添加爲公司對象。我的問題在於,如果我在循環內做[[Company alloc]init];,我將創建一個內存泄漏。如果alloc-init離開循環,所有的值都是一樣的。什麼是最好的方法?下面 代碼:迭代通過NSMutableArray添加數組中的對象

resultArray = [[NSMutableArray alloc]init]; 
responseArray = [allDataDictionary objectForKey:@"companies"]; 

Company *com = [[Company alloc]init]; 
      //Looping through the array and creating the objects Movie and adding them on a new array that will hold the objects 
      for(int i=0;i<responseArray.count;i++){ 


       helperDictionary =(NSDictionary*)[responseArray objectAtIndex:i]; 

       com.title = [helperDictionary objectForKey:@"company_title"]; 
       NSLog(@"company title %@",com.title); 
       [resultArray addObject:com]; 

      } 

公司標題總是結果陣列中的相同的值。如果我將公司的alloc-init放入循環中,則值是正確的。

+1

您使用ARC嗎? – dreamlax

回答

2

我假設你想爲字典中的每個條目創建一個新的Company對象?在這種情況下,您必須每次創建一個新實例:

for (NSDictionary *dict in responseArray) { 
    Company company = [[Company new] autorelease]; 
    company.title = dict[@"company_title"]; 
    [resultArray addObject:company]; 
} 
+0

每次使用相同的變量名創建新的實例會導致泄漏,對吧? – BlackM

+0

@BlackM號您正在存儲對數組中對象的引用。 – trojanfoe

+0

我讀過,如果你在一個循環中初始化一個對象,你將失去對該對象的引用,並且它不能被釋放。這完全錯了嗎?感謝您的回答 – BlackM