遍历 NSMutableArray 以在数组中添加对象
Iterate through NSMutableArray to add object in array
我收到了很多公司的 JSON 回复。
然后我遍历数组以将它们添加为 Company 对象。我的问题是,如果我在循环内执行 [[Company alloc]init];
,我将造成内存泄漏。如果我在循环外分配初始化,我的所有值都是相同的。什么是最好的方法?
代码如下:
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];
}
公司名称在结果数组中始终是相同的值。如果我将 Company alloc-init 放入循环中,则值是正确的。
我假设您想为字典中的每个条目创建一个新的 Company
对象?在这种情况下,您必须每次都创建一个新实例:
for (NSDictionary *dict in responseArray) {
Company company = [[Company new] autorelease];
company.title = dict[@"company_title"];
[resultArray addObject:company];
}
我收到了很多公司的 JSON 回复。
然后我遍历数组以将它们添加为 Company 对象。我的问题是,如果我在循环内执行 [[Company alloc]init];
,我将造成内存泄漏。如果我在循环外分配初始化,我的所有值都是相同的。什么是最好的方法?
代码如下:
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];
}
公司名称在结果数组中始终是相同的值。如果我将 Company alloc-init 放入循环中,则值是正确的。
我假设您想为字典中的每个条目创建一个新的 Company
对象?在这种情况下,您必须每次都创建一个新实例:
for (NSDictionary *dict in responseArray) {
Company company = [[Company new] autorelease];
company.title = dict[@"company_title"];
[resultArray addObject:company];
}