BlackM
BlackM

Reputation: 4071

Iterate through NSMutableArray to add object in array

I have a JSON response with an array of companies. Then I am iterating through the array in order to add them as Company objects. My issue here is that If I do [[Company alloc]init]; inside the loop I will create a memory leak. If I alloc-init out of the loop all my values are the same. What is the best approach? Code below:

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 title is always the same value in the result array. If I put the Company alloc-init in the loop the values are correct.

Upvotes: 0

Views: 538

Answers (1)

trojanfoe
trojanfoe

Reputation: 122458

I assume you want to create a new Company object for each entry in the dictionary? In that case you must create a new instance each time:

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

Upvotes: 2

Related Questions