且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何正确地通知委托人该实例不再需要?

更新时间:2022-11-22 20:45:50

老实说,我认为与其尝试模拟一个保留自动释放功能,还不如尝试调用委托方法messageViewFadedOut:您不在乎是否已释放对消息视图的拥有引用. willFadeOut: 方法的协定可能会假设它不会被释放,但是 fadedOut:didFadeOut: 方法对于被释放的对象应该可以.

To be honest, I think that rather than trying to emulate a retain-autorelease, you should make sure that by the time the delegate method messageViewFadedOut: is called you don't care if the owning reference to your message view is released. The contract for a willFadeOut: method may assume it won't be deallocated, but a fadedOut: or didFadeOut: method should be okay with the object being deallocated.

对于您的dealloc方法,一种理想的解决方案是通过取消正在发生的任何活动淡出动画(在某处保留对其的引用)来专门避免您所讨厌的讨厌的随机错误.这样一来,您就不必关心它到达dealloc的方式或时间,因为dealloc知道做X可以防止死后留下任何对象状态或视觉异常.

An ideal solution would be for your dealloc method to specifically avoid the nasty random bugs you are dreading, by cancelling any active fadeout animation that is occurring (hold a reference to it somewhere). That way you don't care how or when it gets to dealloc, because dealloc knows to do X to prevent leaving any object state or visual anomalies behind when it dies.

因此,只需使用您的解决方案(performSelector:withObject:afterDelay:)或GCD块:

So just use your solution (performSelector:withObject:afterDelay:) or maybe a GCD block:

- (void)fadedOut:(NSString*)animationID finished:(NSNumber*)finished context:(void*)context
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 250 * NSEC_PER_MSEC), // 250ms
                   dispatch_get_current_queue(),
                   ^{
                        [self.delegate messageViewFadedOut:self];
                   });
}

此外,ARC可能会立即autorelease,为什么不多次测试该代码段并查看会发生什么呢?在dealloc中放置一个断点,并在方法返回之前查看是否已调用该断点.

Besides, ARC might just autorelease immediately, why don't you test that code section a bunch of times and see what happens? Put a breakpoint in dealloc and see if it's called before the method returns.