iPhone-scheduledTimerWithTimeInterval 是否保留 userInfo 参数?
在那段代码中,我有两个 NSLog 都表示 dict 的保留计数为 1。 由于如果数组中有很多对象,计时器可能会在很长一段时间内触发,我可以保留给用户信息的字典吗?因为我猜它是自动释放的,而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
}
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* 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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
苹果NSTimer文档说它会保留userInfo。以下引用自文档...
你的第二个 NSLog 说 1,所以我猜它已经被自动释放了,但计时器仍然保留它。
编辑:正如 bbum 所建议的,我们不应该依赖保留计数。所以我们很幸运,医生清楚地说明了这一点。
Apple NSTimer document say that it will retain the userInfo. Below is quoted from the document...
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.
正如 Khomsan 所说,文档明确指出该对象被保留。
故事结束。
retainCount
没用;不要调用它。对象的绝对保留计数是一个实现细节。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.在尝试获取其 userInfo 之前不要使 NSTimer 无效。
do not invalidate NSTimer before attempting to its userInfo.