迭代通过NSMutableArray添加数组中的对象

问题描述:

我有一个公司的数组的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

我假设你想为字典中的每个条目创建一个新的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