迭代通过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放入循环中,则值是正确的。
答
我假设你想为字典中的每个条目创建一个新的Company
对象?在这种情况下,您必须每次创建一个新实例:
for (NSDictionary *dict in responseArray) {
Company company = [[Company new] autorelease];
company.title = dict[@"company_title"];
[resultArray addObject:company];
}
您使用ARC吗? – dreamlax