Reputation: 781
I am developing an IOS application. How can I get the object from NSArray list. What is the best way to avoid getting memory error? Can you tell me the correct method? Thanks
Person *person = [[[Person alloc] init] autorelease];
person = [self.userFavourites objectAtIndex:0];
Person *person = [self.userFavourites objectAtIndex:0];
[person retain];
//Make the required action
[person release];
Upvotes: 1
Views: 7007
Reputation: 13783
Recommendation 3:
Use ARC and modern objective-c so you write less code:
Person *person = self.userFavourites[0];
Upvotes: 2
Reputation: 15213
Person *person = [self.userFavourites objectAtIndex:0];
the userFavourites
array retains all elements inside and when you get an element it comes autoreleased.
EDIT:
Recommendation 1 - makes no sense to alloc init autorelease a Person object and then get different person from the array.
Recommendation 2 - you don't need to retain the object, as the array retains it. You only need to retain it if you need it outside your scope
Upvotes: 5
Reputation: 1296
Why don't you use ARC? It makes your life easier...
However, I would go with recommendation 1, as the autorelease knows how to handle the objects, and it shouldn't give a memory error.
Any more help?
Upvotes: 1