A simple program:
-(void)doSomething {
NSLog(@\"self rc=%d\", [self retainCount]);
[self performSelector:@selector(doMe:) withObject:nil afterDelay:0 inM
From the -[NSObject performSelector:withObject:afterDelay:inModes:] documentation:
2013/11/01 Answer
The docs appear to be updated, as expected, now they don't say the target object is retained however they still mention an scheduled timer in the runloop.
If an NSTimer is used then the object must be retained by somebody or there would be no guarantee the selector can be performed since no-one could assure the object would be still alive. If not using ARC's weak
it will crash.
In my opinion, Apple edited its documentation to not mention implementation details, although I think it is pretty obvious.
Above document does NOT mention the word retain at all however, it does NOT mean the target is is not retained.
This is what I tried in the debugger in the simulator iOS7.0:
(lldb) p (int)[self retainCount]
(int) $1 = 8
(lldb) expr (void)[self performSelector:@selector(description) withObject:nil afterDelay:1.0]
(lldb) p (int)[self retainCount]
(int) $2 = 9
(lldb) expr (void)[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(description) object:nil]
(lldb) p (int)[self retainCount]
(int) $3 = 8
Conclusion: the object is retained, but it is not something we should care about. Mister solved :p
Previous Answer: (still valid)
This method retains the receiver and the anArgument parameter until after the selector is performed.
Because if the object is not retained, the object might be released before it gets executed and your app will crash.
Is the same logic when you set and try to fire a method using NSTimers. When the timer is actually fired if the target object does not exist anymore (is released) your app will crash. So performSelector:withObject:afterDelay:...
and its friends are here to make our life a little bit easier because it makes sure the app won't crash when the timer is fired ;)
Hope it helps
You seem to be wrongly believing that the NSLog in doMe:
will execute before the second one in doSomething:
. That's wrong. The performSelector:afterDelay:…
methods still schedule the message with the runloop even if the delay is 0, so it will execute on the next runloop iteration.
Besides that, there's pretty much no good reason to be looking at an object's retain count — and if you do look, don't trust what you see. The result of the retainCount
method is confusing at best and outright deceptive at worst — for one obvious and extremely common example, the retain count does not reflect autoreleases.