NSTimer内存管理问题
默认情况下,alloc
或copy
方法返回的对象的retain count
等于1,所以你必须自己释放它。
但是通过 NSTimer 示例代码
// in one method start the timer (which myTimer is an Class Instance) myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(method:) userInfo:nil repeats:YES]; // in another method [myTimer invalidate]; myTimer = nil;
我的问题是为什么 [NSTimer sche**] 返回一个您不需要保留的对象,但您可以在任何地方访问它。并且您不需要释放它,而只需对其调用 invalidate
即可。
By default an object returnd by method alloc
or copy
has retain count
equals to 1, so you have to release it by yourself.
But through NSTimer sample codes
// in one method start the timer (which myTimer is an Class Instance) myTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(method:) userInfo:nil repeats:YES]; // in another method [myTimer invalidate]; myTimer = nil;
My question is why [NSTimer sche**] returns an object that you needn't retain, but you can access it anywhere. And you needn't release it but only invoke invalidate
on it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
该实例保留在分配给它的运行循环中。
保留计数保持在零以上,直到运行循环释放它。
因此您可以访问该对象,直到发生这种情况。
来自 NSTimer 文档:
然后具体来说:
因此,您使用的方法会自动适用于当前的运行循环。
The instance is retained in the run loop that it is assigned to.
The retain count remains above zero until the run loop releases it.
So you can access the object until that happens.
From the NSTimer docs:
And then specifically:
So the method you've used works with the current run loop automatically.