开发者

iPhone - does scheduledTimerWithTimeInterval retain userInfo param ?

开发者 https://www.devze.com 2023-03-24 05:41 出处:网络
In that piece of code, I have both NSLog that says dict has a retain count of 1. As the timer can be triggered in a long time if there are many objects into the array, May I retain dict given into use

In that piece of code, I have both NSLog that says dict has a retain count of 1. As the timer can be triggered in a long time if there are many objects into the array, May I retain dict given into user info ? Because I guess it's autorelease, and the scheduledTimerWithTimeInterval does not seems to retain it.

Theoricaly ? Practically ?

- (void) doItWithDelay
{
    NSArray* jobToDo = /* get an autorelease array */

    NSTimeInterval nextLaunch = 0.1;
    int i=1;

    for (NSDictionary开发者_如何学C* dict in jobToDo) {
        NSLog(@"dict %d has %d retain count", i++, [dict retainCount]);

        // HERE [dict retain] ???
        [NSTimer scheduledTimerWithTimeInterval:nextLaunch target:self selector:@selector(doIt:) userInfo:dict repeats:NO];   
        nextLaunch += 1.0;
    }
}

- (void) doIt:(NSTimer*)theTimer 
{    
    NSDictionary* dict = [theTimer userInfo];

    NSLog(@"dict has now %d retain count", [dict retainCount]);

    // Do some stuff with dict
}


Apple NSTimer document say that it will retain the userInfo. Below is quoted from the document...

The object you specify is retained by the timer and released when the timer is invalidated.

Your second NSLog say 1, so i guess it already been autoreleased but the timer still retain it.

EDIT: As bbum suggested, we should not rely on retain count. So we're lucky that the doc state it clearly.


As Khomsan said, the docs explicitly state that the object is retained.

End of story.

retainCount is useless; don't call it. The absolute retain count of an object is an implementation detail.


do not invalidate NSTimer before attempting to its userInfo.

0

精彩评论

暂无评论...
验证码 换一张
取 消