iOS: Properties – allocating and releasing objects - objective-c

I am struggling in iOS (4) with allocating objects in one scope and releasing it in another scope. I am using properties as pointers to the objects. The object is allocated and initialized in one instance class method and I release it in the class’ dealloc method. The properties are declared with retain. Besides having problems with using properties likes this I also find it cumbersome to alloc and initialize the object and set the property.
NSObject *object = [[NSObject alloc] init];
Self.myProperty = object;
[object release];
I tried
self.myObject = [[NSObject alloc] init];
However that gave me a memory leak.
My question: Do I have to make this temporary object or is there a more elegant way of doing this?
A followup question: Do I have to both set the property to nil and release the autogenerated ivar?
[self setMyProperty:nil], [myProperty release];
When XCode 4 generates property stubs for you it puts [self setMyProperty:nil] in viewDidUnload and [_myProperty release] in dealloc.

First question:
autorelease is your friend:
self.myObject = [[[NSObject alloc] init] autorelease];
Second question:
No, it's redundant, but harmless since the second operation will do nothing ([nil release] is safe).
I'd advise using the self.XXX = nil; construct, as it's safer and very clear/readable.

The self. notation is running through the synthesized setter which does a retain, which is why you need to do the autorelease on the init object. Conversely, you could leave off the self. and just use
myObject = [[NSObject alloc] init;
This line just sets the myObject pointer to the retained object, and you would not have any leak.
Here was my question from a while back along the same lines as yours:
MKReverseGeocoder autorelease/release question in Apple's CurrentAddress sample

Related

In Objective-C MRR, if foo is a retain property, then self.foo = [[Foo alloc] init] will need to be released immediately?

I am using ARC but reading the MRR part of Objective-C, and it seems like if a property of ViewController is (for non-ARC):
#property (retain, nonatomic) Foo *foo;
then the viewDidLoad of ViewController will need to do a release right after alloc and init:
- (void)viewDidLoad
{
[super viewDidLoad];
self.foo = [[Foo alloc] init];
[self.foo release];
}
Otherwise, the retain will increment the reference count of the Foo object once when it is assigned to _foo (the instance variable), and alloc also increment the reference count once, so it is claiming ownership twice, and therefore, there needs to be a release right after the alloc and init?
I just feel it is a bit weird looking because an alloc is immediately followed by a release this way.
(If we do is a self.foo = [Foo fooByString: #"hello"], then one ownership is claimed by the autorelease pool, and one claimed by ViewController, and at the end of the event loop, the autorelease pool drains, and unclaim one ownership, and therefore the Foo object is correctly owned once only. (but if Foo doesn't have such methods and only have alloc and init, then the immediate release is needed.))
You're essentially correct, though there are a few ways that it was typically done to make it look less awkward:
Foo* someFoo = [[Foo alloc] init];
self.foo = someFoo;
[someFoo release];
Or more succinctly:
self.foo = [[[Foo alloc] init] autorelease];
If you are on your viewController's constructor/init, what you need to do is:
_foo=[[Foo alloc] init];
To avoid the unnecessary release call, since the alloc/init creates a non-autorelease instance of foo. Also, it will remove the need to have the autorelease pool to work on an object that we have complete control of its initialization. You know you want foo to be owner by your viewController. It's unnecessary to claim ownership twice just to have the retain count decreased at the return of the runloop.

Strange memory only when using copy

I have a class named SomeClass. in its init I have a lot of lines like:
SomeProperty_ = [[SomeObject alloc] initWithSomething];
While the properties are declared as
#property(retain) SomeObject *SomeProperty;
and defined as
#synthesize SomeProperty = SomeProperty_;
When I allocate objects of SomeClass and later release them, everything works fine and there are no memory leaks. However, when I copy an object of SomeClass and later release it, all the lines like
SomeProperty_ = [[SomeObject alloc] initWithSomething];
are marked as a memory leak in Instruments. this is also correct as I get memory warning and later crash if I use this a lot.
However if I make a method named dealloc like:
-(void) dealloc
{
self.SomeProperty = nil;
[super dealloc];
}
Everything is fine with copies as well and no memory warning or leaks.
I think this is because of my copy implementation:
-(id)copy
{
SomeClass *copy = [[SomeClass alloc] init];
copy.SomeProperty.somePOD = self.SomeProperty.somePOD;
return copy;
}
Where is the problem? what can I do to resolve it without the custom dealloc?
The first things I can think of is:
How your somePOD is set as far as #property(???)
And when you say :
"However, when I copy an object of SomeClass and later release it, all the lines like
SomeProperty_ = [[SomeObject alloc] initWithSomething];
are marked as a memory leak in Instruments. this is also correct as I get memory warning and later crash if I use this a lot."
You are referring to call made in your init method?
Because if your not, you are bypassing a setter and the object that was in that variable before this assignment will leak.
You must either use a custom dealloc method or start using Automatic Reference Counting (ARC).
When you call [[SomeObject alloc] init...], you get ownership of the new object, so you must release the object when you are done with it. Setting self.SomeProperty to nil does the release because you declare the property with the retain attribute.
You do this in your dealloc method if you want to own the SomeObject object until your SomeClass object dies. If you use ARC, it will generate the dealloc method for you.

Acceptable ways to release a property

Assume there is a class with the following interface:
#import <Foundation/Foundation.h>
#interface MyClass : NSObject {
}
#property (nonatomic, retain) NSDate* myDate;
-(void)foo;
#end
and the following implementation:
#import "MyClass.h"
#implementation MyClass
#synthesize myDate = _myDate;
- (void)dealloc
{
[_myDate release];
[super dealloc];
}
-(void)foo
{
NSDate* temp = [[NSDate alloc] init];
self.myDate = temp;
[temp release];
}
#end
1) In the function foo will releasing like this ensure that the retain count of the objects is properly maintained (i.e. no memory is leaked and no unnecessary releases are performed).
NSDate* temp = [[NSDate alloc] init];
self.myDate = temp;
[temp release];
2) Same question as in 1) except applied to the following technique:
self.myDate = [[NSDate alloc] init];
[self.myDate release]
3) Same question as in 1) except applied to the following technique:
self.myDate = [[NSDate alloc] init] autorelease];
4) Same question as 1) but applied to the following technique:
self.myDate = [[NSDate alloc] init];
[_myDate release]
5) Same question as 1) but applied to the following technique:
[_myDate release];
_myDate = [[NSDate alloc] init];
1) Just fine.
2) Possibly unsafe, and will trigger warnings in the latest LLVM static analyzer. This is because the object returned by the getter method may not be the same one you passed to the setter. (The setter may have made a copy, for example, or may have failed validation and set a nil instead.) This would mean you were leaking the original object and over-releasing the one the getter gave back to you.
3) Just fine; similar to 1 but the release will come when the current autorelease pool is drained instead of immediately.
4) Possibly unsafe, but will not trigger warnings that I've seen. The issue is similar to the one described in 2; the object in the ivar may not be the one you passed to the setter.
5) Safe, but will not use the setter method or notify any observers of the property.
In the case where the property is a retain type, and both the getter and setter are just the synthesized versions, all of the above examples will work. However, they don't all represent best practice, and may trigger analysis warnings. The goal should be that the -foo method works correctly regardless of how myDate is managing its memory. Some of your examples above don't do that.
If, for example, you decided to change the property to copy later, you should not be required to change any other code to make it work correctly. In cases 2 and 4, you would be required to change additional code because the foo method is assuming that the setter will always succeed and always set the original object.
5) is a bug - it leaks the old instance as it doesn't get released but just reassigned.
1) is clean and the best way to go.
4) is ok but puts some burden on the memory system - the object might live longer than needed.
2) technically ok, but you shouldn't directly retain/release the property - that's what the syntactic sugar is for!
3) technically ok, but also bypasses the property and relies on implementation details.
2) and 3) are discouraged and ask for trouble in the future when some part of code changes.
Edit: New code doesn't leak in 5). It has the same downsides, though.
There's a reason why we got support for properties, and it does a great and consistent use. You should only consider bypassing them if your time profile gives very clear hints that this is a bottle neck (unlikely).
First, if you want to avoid the alloc, release, autorelease etc... you can call a date factory method which doesn't start with alloc.
For example:
self.myDate = [NSDate date];
The date class factory method does an autorelease according to the convention rules. Then the property retains it.
Alloc will give it a retain count of 1, then assigning the property will retain it. Since your class is now retaining it from the property, you can release it to counter act the alloc.
Ditto but that's a wierd round about way to do it.
3 is equivalent to the code I had above ([NSDate date]);
In this case, the property will retain it (after alloc incremented the retain count), then you're going under the covers to decrement it. Works but I wouldn't recommend doing that since you're synthesized (retain) property will do that for you.
the pattern of release and renew is merely a semantic. You get a retain count for each of the following.
myObject = [Object alloc]
objectCopy = [myObject copy]
myNewObject = [Object newObjectWithSomeProperties:#"Properties"] // Keyword here being new
// And of course
[myObject retain]
a property with the modifier (retain) or (copy) will have retain count on it.
the backing store _myDate is merely where the object is actually stored.
when you get a retain count you need to release.
Either immediately with the [myObject release] message or let the pool release it with [myObject autorelease]
Whatever the case, Any retain you are given (implicit or explicit) will need to be released. Otherewise the garbage collector will not collect your object and you will have a memory leak.
the most common usage in
Object myObject = [[[Object alloc] init] autorelease]; // Use this when you dont plan to keep the object.
Object myObject = [[Object alloc] init];
self.myProperty = [myObject autorelease]; // Exactally the same as the Previous. With autorelease
// Defined on the assignment line.
self.myProperty = [[[Object alloc] init] autorelease]; // Same as the last two. On one line.
I will demonstrate other possibilities
// Uncommon. Not incorrect. But Bad practice
myObject = [[Object alloc] init];
self.myProperty = myObject;
// Options
[_myProperty release] // Bad practice to release the instance variable
[self.myProperty release] // Better practice to Release the Property;
// releasing the property or the instance variable may not work either.
// If your property is using the (copy) modifier. The property is copied rather then retained.
// You are still given a retain count.
// But calling release on a copy will not release the original
[myObject release]; // Best Practice. Good when Threading may run the autorelease pool
[myObject autorelease]; // As good as the previous.
// But may leave your object in memory during long operations
Essentially, your object given a retain will be the same object in the Property the Variable and the Instance Variable. Releasing on any of them will release it.
However. Best practice says that if you retain an object. Best to call release on the same variable of that object. Even if Autorelease and retain is called on the other side.
// Other items that give you a retain count.
Core Media or Core Anything Functions that have Create Or Copy in the name.

Objective C: Newbie question about allocation, retain and release [duplicate]

This question already has answers here:
Objective-C: alloc of object within init of another object (memory management)
(3 answers)
Closed 8 years ago.
New to OC, many years of C, C++, C#, mind is kind of boggled now.
Given:
// AnInterface.h
#interface AnInterface : NSObject
{
}
#property (retain) SomeObject* m_Object;
// AnInterface.m
#import "AnInterface.h"
#synthesize m_Object;
-init
{
self= [super init];
if(!self)
return (nil);
SomeObject* pObject= [[SomeObject alloc] init];
self.m_Object= pObject;
[pObject release];
}
I am pretty sure the above is correct. However,
why not just do:
self.m_Object= [[SomeObject alloc] init];
Does that work as well? Is it in violation of some memory management tenet? It seems like it should work, one line rather than three, but I am certain I must be missing something....
Any insight would be appreciated.
The reason is because you defined the property m_Object to retain so it would result in a memory leak because alloc/init call results in a retain of +1 then property will retain giving it at least a retain count of +2. If you would like to make it one line feel free to abuse the auto release pool.
self.m_Object= [[[SomeObject alloc] init] autorelease];
That leaks the object. Since alloc returns an owning reference, and retain claims ownership a second time, you need to call release to balance the alloc or the object will think you want to hold onto it forever and never be deallocated.
self.m_Object = [[SomeObject alloc] init];
This causes an over-retain. You get one claim of ownership for the alloc, and another through the setter, which is declared as retaining the new value. Since you only have one pointer to the new value, you have too many claims. When the setter is used again:
self.m_Object = anotherObject;
the original object will receive only one release message, and you will lose the pointer. Since you had two claims on the object, it will not be deallocated, and you will have a leak.
The property access: self.m_Object = obj; is translated by the compiler into [self setM_Object:obj];. That is, the setter method for the property, created by the #synthesize directive, is called. That setter method retains its argument. The other option is to use the ivar directly in your init method:
-init {
//...
m_Object = [[SomeObject alloc] init];
//...
}
then you have only one claim on this object, caused by the use of alloc. Since you also have one reference to the object, this is correct.

Why does this create a memory leak (iPhone)?

//creates memory leak
self.editMyObject = [[MyObject alloc] init];
//does not create memory leak
MyObject *temp = [[MyObject alloc] init];
self.editMyObject = temp;
[temp release];
The first line of code creates a memory leak, even if you do [self.editMyObject release] in the class's dealloc method. self.editMyObject is of type MyObject. The second line incurs no memory leak. Is the first line just incorrect or is there a way to free the memory?
The correct behavior depends on the declaration of the editMyObject #property. Assuming it is delcared as
#property (retain) id editMyObject; //id may be replaced by a more specific type
or
#property (copy) id editMyObject;
then assignment via self.editMyObject = retains or copies the assigned object. Since [[MyObject alloc] init] returns a retained object, that you as the caller own, you have an extra retain of the MyObject instance and it will therefore leak unless it there is a matching release (as in the second block). I would suggest you read the Memory Management Programming Guide[2].
Your second code block is correct, assuming the property is declared as described above.
p.s. You should not use [self.editMyObject release] in a -dealloc method. You should call [editMyObject release] (assuming the ivar backing the #property is called editMyObject). Calling the accessor (via self.editMyObject is safe for #synthesized accessors, but if an overriden accessor relies on object state (which may not be valid at the calling location in -dealloc or causes other side-effects, you have a bug by calling the accessor.
[2] Object ownership rules in Cocoa are very simple: if you call a method that has alloc, or copy in its signature (or use +[NSObject new] which is basically equivalent to [[NSObject alloc] init]), then you "own" the object that is returned and you must balance your acquisition of ownership with a release. In all other cases, you do not own the object returned from a method. If you want to keep it, you must take ownership with a retain, and later release ownership with a release.
Your property is declared "retain" meaning that it the passed in object is automatically retained.
Because your object already had a reference count of one from alloc/init there's then two references and I'm assuming only one release (in your destructor).
Basically the call to self.editMyObject is really doing this;
-(void) setEditMyObject:(MyObject*)obj
{
if (editMyObject)
{
[editMyObject release];
editMyObject = nil;
}
editMyObject = [obj retain];
}
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
The first version creates an object without a matching release. When you alloc the object, it means you are an owner of that object. Your setter presumably retains the object (as it should), meaning you now own the object twice. You need the release to balance the object creation.
You should read the Cocoa memory management guide if you plan to use Cocoa at all. It's not hard once you learn it, but it is something you have to learn or you'll have a lot of problems like this.
Everyone else has already covered why it causes a memory leak, so I'll just chime in with how to avoid the 'temp' variable and still prevent a memory leak:
self.editMyObject = [[[MyObject alloc] init] autorelease];
This will leave your (retain) property as the sole owner of the new object. Exactly the same result as your second example, but without the temporary object.
It was agreed and explained that the code below does not have a leak
(assuming #property retain and #synthesize for editMyObject) :
//does not create memory leak
MyObject *temp = [[MyObject alloc] init];
self.editMyObject = tempt;
[temp release];
Question : is anything wrong with the following code that does not use a temp pointer ?
//does not create memory leak ?
self.editMyObject = [[MyObject alloc] init];
[editMyObject release];
To me this looks ok.