Objective-C。对象的值设置为零。但是基于 NSTimer 的方法仍在执行
Objective-C. Object's value set to nil. But NSTimer based method is still executing
我有一个简单的应用程序,其中 class Person 有一个 属性 doggo 类型 狗.
对象 doggo 从 doggo[=43= 的那一刻起增加它的 hungerLevel 属性 ] 有一个值(从一些 ViewController 调用 KVO)。
-(void)dogGetsHungry {
[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
self.hungerLevel += 10;
NSLog(@"Hunger level grows");
}];
}
现在,一些 ViewController 正在观察 doggo 的 hungerLevel。当 hungerLevel 超过,比方说,160,doggo 逃脱 (self.person.doggo = nil;
).
但是 NSTimer 永远不会停止。它将永远执行。我觉得可能跟retain cycle有关系,所以我把person的属性doggo设置为weak,但是我收到这个警告
Assigning retained object to weak property; object will be released after assignment
我认为这是一个很好的用例,其中类型 Dog 的 属性 应该是弱的,以避免 strong retain cycles.如果有人也能帮助我理解这一点,我将不胜感激。
非常感谢您的帮助。
旁注:我正在使用 KVO,所以我可以更好地了解它。
But the NSTimer will never stop. I thought it may have something to do with the retain cycle
runloop 保留了预定的计时器。见 NSTimer:
Run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.
Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A nonrepeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method.
您确实需要引用计时器来调用 invalidate
,将从 scheduledTimerWithTimeInterval
返回的计时器存储在 属性 中。
我有一个简单的应用程序,其中 class Person 有一个 属性 doggo 类型 狗.
对象 doggo 从 doggo[=43= 的那一刻起增加它的 hungerLevel 属性 ] 有一个值(从一些 ViewController 调用 KVO)。
-(void)dogGetsHungry {
[NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
self.hungerLevel += 10;
NSLog(@"Hunger level grows");
}];
}
现在,一些 ViewController 正在观察 doggo 的 hungerLevel。当 hungerLevel 超过,比方说,160,doggo 逃脱 (self.person.doggo = nil;
).
但是 NSTimer 永远不会停止。它将永远执行。我觉得可能跟retain cycle有关系,所以我把person的属性doggo设置为weak,但是我收到这个警告
Assigning retained object to weak property; object will be released after assignment
我认为这是一个很好的用例,其中类型 Dog 的 属性 应该是弱的,以避免 strong retain cycles.如果有人也能帮助我理解这一点,我将不胜感激。
非常感谢您的帮助。
旁注:我正在使用 KVO,所以我可以更好地了解它。
But the NSTimer will never stop. I thought it may have something to do with the retain cycle
runloop 保留了预定的计时器。见 NSTimer:
Run loops maintain strong references to their timers, so you don’t have to maintain your own strong reference to a timer after you have added it to a run loop.
Once scheduled on a run loop, the timer fires at the specified interval until it is invalidated. A nonrepeating timer invalidates itself immediately after it fires. However, for a repeating timer, you must invalidate the timer object yourself by calling its invalidate method.
您确实需要引用计时器来调用 invalidate
,将从 scheduledTimerWithTimeInterval
返回的计时器存储在 属性 中。