Reputation: 20564
> .h file:
NSString *myString;
@property (nonatomic, retain) NSString *myString;
> .m file:
self.myString = [[NSString alloc] init];
If i'm not wrong i will end up with an NSString instance with retain count of +2. Right?
I'm curious because Apple's example for Location uses "self." for initialization. Why? I checked and it does show retain count to be +2.
Upvotes: 0
Views: 961
Reputation: 8823
In your Modification 1, you're setting your instance variable directly to an autoreleased object. This means that at the end of the event loop your locationManager
will be released and in this case, you'll then have a reference to a now unused block of memory.
Your Modification 2 looks correct to me, as does the sample code you've started from.
Upvotes: 1
Reputation: 119106
To answer your first question:
Yes, the retain count would be two.
To answer your second question:
The reason for using:
self.myString = x;
which is equivalent to:
[self setMyString:x];
is so that all of the property handling code is properly executed. This includes KVO notifications, and the code that automatically retains x as it is passed in.
If you were to simply set:
myString = x;
in the .m file, you would bypass all of that hidden property setting code, and simply set the myString member variable to a pointer to x.
Upvotes: 7
Reputation: 96323
Mustafa: Yes, you're correct. (The property should be declared as copy
, not retain
, but that's another matter.)
Upvotes: 3