在父对象被释放后延迟释放 ivar
我有一个 TouchInfo 类,它有一个 MotionStreak 类的 ivar。
@interface TouchInfo : NSObject {
MotionStreak *streak;
}
...
@end
这个类主要处理触摸事件并绘制跟随触摸的运动条纹。我想在用户释放手指时释放与特定触摸关联的 TouchInfo 实例,但我希望运动条纹在淡出之前保留 0.5 到 1.0 秒,所以我不能在TouchInfo
类的dealloc
方法中释放streak
ivar。
我使用计时器来延迟 streak
ivar 的释放,使用自定义计时器类,如下所示:
- (void)dealloc {
[self timedReleaseStreak];
[super dealloc];
}
- (void)timedReleaseStreak {
[streak fadeoutWithDelay:1.0];
[[TimerHandler sharedTimer] object:streak action:@selector(release) delay:1.0];
}
到目前为止,它工作正常,没有任何崩溃。但我想知道我这样做是否错误,是否有更好的推荐方法。请指教。
p/s:拜托,对ARC没有任何建议;我还没有自动释放手动引用计数魔法:P
I have a class TouchInfo that has an ivar of class MotionStreak.
@interface TouchInfo : NSObject {
MotionStreak *streak;
}
...
@end
This class basically handles the touch event and draws a motion streak that follows the touch. I want to release the instance of TouchInfo
that associates with a particular touch when the user releases his/her finger, but I want the motion streak to remain for 0.5 to 1.0 second before fading out, so I cannot release the streak
ivar in the dealloc
method of TouchInfo
class.
I'm using timer to delay the release of streak
ivar, using a custom timer class as follows:
- (void)dealloc {
[self timedReleaseStreak];
[super dealloc];
}
- (void)timedReleaseStreak {
[streak fadeoutWithDelay:1.0];
[[TimerHandler sharedTimer] object:streak action:@selector(release) delay:1.0];
}
So far it works without any crashes. But I'm wondering if I'm doing this wrongly, and if there is a better and a recommended way of doing it. Please advice.
p/s: Please, no advice on ARC; I am yet to autorelease the manual reference counting wizardry :P
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于块在复制时会保留它们引用的任何对象,因此您可以使用它们来实现动画,这将防止对象在块被释放之前被释放。
下面是一个使用
+[UIView animateWithDuration:animations:completion:]
淡出视图并将其从视图层次结构中删除的示例。为了稍后使用完成块,必须将其复制到堆中,这将导致视图被保留。请注意,我将
streak
ivar 复制到局部变量,并在块中使用它。如果您尝试直接使用 ivar,它将保留 self,这将不起作用,因为您已经开始释放过程。Since blocks retain any objects they reference when they get copied, you could implement your animation using them, which will prevent the object from being deallocated until the block is deallocated.
Here is an example which uses
+[UIView animateWithDuration:animations:completion:]
to fade the view out and remove it from the view hierarchy. In order to use the completion block later, it has to copy it to the heap, which will result in the view being retained.Note that I copied the
streak
ivar to a local variable, and used that in the block. If you try to use the ivar directly, it will retainself
instead, which won't work because you are already starting the deallocation process.