Ethan Allen
Ethan Allen

Reputation: 14835

Which way is the correct way to allocate memory with a property?

Which way is correct?

NSString *c = [[NSString alloc] init];
self.character = c;
[c release];

or

self.character = [[NSString alloc] init];

And why? Thanks.

Upvotes: 0

Views: 156

Answers (4)

Ethan Allen
Ethan Allen

Reputation: 14835

The answer to this now with iOS 5 is to use ARC.

Upvotes: 0

typeoneerror
typeoneerror

Reputation: 56968

The answer depends on your @property definition. Likely it's something like (retain) or (copy) for an NSString. In that case, assigning to self.character will increment the retain count. So the bottom:

self.character = [[NSString alloc] init];

You've set the retain count to 1 with the alloc and self.character will also retain it for a count of 2, so that'll leak. Should be

self.character = [[[NSString alloc] init] autorelease];

or the top version.

Upvotes: 1

user94896
user94896

Reputation:

It depends on how you've defined your property.

If it's copy or retain, the synthesized setter (setCharacter: in your example) will take ownership of any objects you assign to the property. In this situation your first example is correct. The second would lead to a memory leak as you've claimed ownership of the NSString twice and you will (probably) only relinquish ownership once; thus the memory can never be reclaimed.

If it's assign on the other hand, the setter won't do anything special and your second example would be correct. The first would result in an EXC_BAD_ACCESS error if you tried to do anything with the NSString. I should note that you generally only use assign for primitive types and delegates.

I suggest you have a read over the Memory Management Programming Guide and the Declared Properties section of The Objective-C Programming Language guide.

Upvotes: 3

Seventoes
Seventoes

Reputation: 4840

It depends on how your property is declared. If you used

@property (nonatomic, retain) NSString *someString;

The setter will be created to retain someString, in which case the correct way is your first method. If you used:

@property (nonatomic, assign) NSString *someString;

Your second method will be correct, since it will just assign the pointer and not retain anything.

Upvotes: 4

Related Questions