By convention in Cocoa and Cocoa-touch, any object created using [[SomeClass alloc] initX]
or [SomeClass newX]
is created with a retain count of one. You are responsible for calling [someClassInstance release]
when you're done with your new instance, typically in your dealloc
method.
Where this gets tricky is when you assign your new object to a property instead of an instance variable. Most properties are defined as retain
or copy
, which means they either increment the object's retain count when set, or make a copy of the object, leaving the original untouched.
In your example, you probably have this in your .h
file:
@property (retain) MyObject *editMyObject;
So in your first example:
// (2) property setter increments retain count to 2
self.editMyObject =
// (1) new object created with retain count of 1
[[MyObject alloc] init];
// oops! retain count is now 2
When you create your new instance of MyObject
using alloc
/init
, it has a retain count of one. When you assign the new instance to self.editMyObject
, you're actually calling the -setEditMyObject:
method that the compiler creates for you when you @synthesize editMyObject
. When the compiler sees self.editMyObject = x
, it replaces it with [self setEditMyObject: x]
.
In your second example:
MyObject *temp = [[MyObject alloc] init];
// (1) new object created with retain count of 1
self.editMyObject = temp;
// (2) equivalent to [self setEditMyObject: temp];
// increments retain count to 2
[temp release];
// (3) decrements retain count to 1
you hold on to your new object long enough to release it, so the retain count is balanced (assuming you release it in your dealloc
method).
See also Cocoa strategy for pointer/memory management