0

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.

0

1 Answer 1

2

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];
}
Sign up to request clarification or add additional context in comments.

8 Comments

Creating new instance each time with the same variable name would cause leaks, right?
@BlackM No. You are storing a reference to the object in the array.
I read that if you initialise an object in a loop, you are losing the reference to that object and it can't be freed. Is that completely wrong? Thank you for your answer
Well you are not losing it as you are making the array manage the object. Without the last line, you would have a memory leak, if you are using manual reference counting.
If using manual memory management, then wouldn't company need to be released after being added to the array?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.