hiwordls
hiwordls

Reputation: 781

IOS get object from NSArray

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

Recommendation 1

Person *person = [[[Person alloc] init] autorelease];
        person = [self.userFavourites objectAtIndex:0];

Recommendation 2

Person *person = [self.userFavourites objectAtIndex:0];
[person retain];

//Make the required action

[person release];

Recommendation 3

?

Upvotes: 1

Views: 7007

Answers (3)

Nikos M.
Nikos M.

Reputation: 13783

Recommendation 3:

Use ARC and modern objective-c so you write less code:

Person *person = self.userFavourites[0];

Upvotes: 2

graver
graver

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

Albara
Albara

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

Related Questions