Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

objective c - the effect on retain count of performSelector:withObject:afterDelay:inModes

A simple program:

-(void)doSomething {

 NSLog(@"self rc=%d", [self retainCount]);

 [self performSelector:@selector(doMe:) withObject:nil afterDelay:0 inModes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];

 NSLog(@"self rc=%d", [self retainCount]);
}

-(void)doMe:(id)object {

 NSLog(@"i'm done");

 NSLog(@"self rc=%d", [self retainCount]);

}

Output:

self rc=1

self rc=2

i'm done

self rc=2

Why does the retain count increment to and stay at 2?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...