Well, i am still confused about objective c properties and instance variables.
I create a LocationManager-object in my viewDidLoad. On the one hand the LocationMan is just an instance variable on the other hand it is declared as a property. Have a look at the examples:
First example:
Header:
CLLocationManager* _locationMan;
Implementation:
CLLocationManager* theManager = [[[CLLocationManager alloc] init] autorelease];
_locationMan = theManager;
_locationMan.delegate = self;
Second Example
Header:
CLLocationManager* _locationMan;
@property (retain, nonatomic) CLLocationManager* locationMan;
Implementation:
self.locationMan = [[[CLLocationManager alloc] init] autorelease];
self.locationMan.delegate = self;
Whats the difference between those examples except of that the second one is working and the first one not? What’s going on there with the memory management?
The problem you have in your first example:
is caused by the use of
autorelease.autoreleasecan be seen as meaning: at some point in the near future,releaseautomatically this object. Given the wayautoreleaseis implemented, by means of a release pool, this usually happens the next time the control flow return to the main loop and the release pool is emptied.So, in your first case, you are creating the object and storing it in your ivar; but soon it will be released, and since you don’t have explicitly retained it anywhere else, it will end up being deallocated. When you access it after that, you get the error. If you had not used
autorelease, everything would have worked correctly:In your second example, creation is just the same, meaning, the object will also be flagged for autorelease. But, in this case, you assign it to a property which has got the
retainmodifier. This means that the object will be automatically retained when assigning to the property. So, when the autorelease is actually done (when you get back to the main look, roughly), your object will have already had its retain count incremented by 1; then auto releasing it will not make its retain count go to 0, and the object will not be deallocated.What you have to know clearly is that:
allocwill set the retain count to 1;retainproperties will increment the retain count when assigning to them;autoreleaseis like a delayed release, so that in the mean time (before the release is actually done, which means in the rest of your method and callers up to the main loop) you can use the object safely and thereafter it will be released.