【问题标题】:iPhone - does scheduledTimerWithTimeInterval retain userInfo param ?iPhone-scheduledTimerWithTimeInterval 是否保留 userInfo 参数?
【发布时间】:2011-07-30 23:55:05
【问题描述】:

在那段代码中,我有两个 NSLog 都说 dict 的保留计数为 1。 由于如果数组中有很多对象,可以长时间触发计时器,我可以保留用户信息中给出的字典吗?因为我猜是autorelease,而且scheduledTimerWithTimeInterval 好像没有保留。

理论上? 实用吗?

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

    NSTimeInterval nextLaunch = 0.1;
    int i=1;

    for (NSDictionary* 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
}

【问题讨论】:

    标签: iphone cocoa memory-management nstimer retain


    【解决方案1】:

    Apple NSTimer 文档说它将保留用户信息。以下引用自文档...

    你指定的对象被定时器保留,定时器失效时释放。

    你的第二个 NSLog 说 1,所以我猜它已经被自动释放但计时器仍然保留它。

    编辑:正如 bbum 所建议的,我们不应该依赖保留计数。所以我们很幸运,文档清楚地说明了这一点。

    【讨论】:

    • 对象的绝对保留计数没有意义。你的结论不正确; autorelease 不会直接影响保留。
    【解决方案2】:

    正如 Khomsan 所说,文档明确声明该对象被保留。

    故事结束。

    retainCount 没用;不要叫它。对象的绝对保留计数是一个实现细节。

    【讨论】:

      【解决方案3】:

      在尝试访问其 userInfo 之前不要使 NSTimer 无效。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 2011-06-09
        • 2011-05-14
        • 2011-05-18
        • 2017-03-04
        • 2023-03-15
        相关资源
        最近更新 更多