hzxu
hzxu

Reputation: 5823

iOS non-arc: should I use autorelease when self.property = [[Obj alloc] init]?

If I have the below property:

@property (nonatomic, retain) MyObject *theObject;

then if I want to create a new MyObject, do I:

self.theObject = [[MyObject alloc] init];

or:

self.theObject = [[[MyObject alloc] init] autorelease];

Upvotes: 0

Views: 338

Answers (2)

user529758
user529758

Reputation:

You have to use autorelease. If you don't, the object will have a release count of two (one from alloc, one from the retain by the setter), so when the property is unset, it'll be leaked.

This only applies to strong or retained and copy properties. Assigned and weak properties should just be assigned an alloc-initted object, since they don't alter its reference count.

Upvotes: 2

Abizern
Abizern

Reputation: 150625

If you must - the second.

If you are using the generated setter, you have marked it with retain. Which means that the value stored in that property will be retained for you, so you don't need to pass it an owned object.

Since it is retained, you need to release it in your dealloc.

Upvotes: 2

Related Questions