Property does not seem to be used?
This is something that I came across in the Apple reference material - Sample Code when researching how to use NSTimer, I am not asking about NSTimer as that开发者_如何学Pythons a seperate question but I am curious about the use of the @property, the direct assignment to the iVar (i.e. not using the property setter) and the subsequent release.
@property (nonatomic, retain) NSTimer *updateTimer;
...
@synthesize updateTimer;
...
updateTimer = [NSTimer scheduledTimerWithTimeInterval:.01 target:self selector:@selector(updateCurrentTime) userInfo:p repeats:YES];
...
...
updateTimer = nil;
...
...
// Dealloc method
[updateTimer release];
My question is, does the property get used at all, it seems not? Also the release, does that work, where is the retain if the @property setter is not being used?
The retain is in the definition of the property. (i.e. where it says "(nonatomic, retain)" in brackets.)
If the property had been allocated, it would be retained "automatically" by the setter it at that time.
But just as you say the property itself is never used, so it is never allocated or retained.
The release you can see in the code appears to be simply wrong, just as you say. The ivar was never retained so a release would crash just as Bjorn pointed out.
(Note that they apparently set it to nil -- of course you can send any message at all to nil, but just as you say it's a really silly example. You can't release something you never retained.)
Exactly as you say, the example is a little weird. There was "no reason" to make a property: just as you say it was never used. Conversely, why did they release the ivar - which was never retained.
So in short your suspicions seem to be correct!
There are at least three horrible errors in that code!
You are right, the property is never used as there is no call like self.updateTimer = something
or [self setUpdateTimer:something]
. Sending the release
message in -dealloc
"works" because you reset updateTimer
to nil
. It is perfectly fine to send messages to nil
, but nothing is going to happen. If you did not reset the variable to nil
, the message would have been sent to a deallocated instance and cause an EXC_BAD_ACCESS
exception.
If you use a dot, the property method gets called. Otherwise it is simple assignment. For instance, foo = bar
would be assignment, whereas self.foo = bar
would result in the property method getting called.
Try using self.updateTimer = ...
.
精彩评论