سؤال

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

هل كانت مفيدة؟

المحلول

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.

- (void)dealloc {
    UIView *localStreak = streak;
    [UIView animateWithDuration:1.0 animations:^ {
        localStreak.alpha = 0.0;
    } completion:^ (BOOL finished) {
        [localStreak removeFromSuperview];
    }];
    [streak release];
    [super dealloc];
}

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 retain self instead, which won't work because you are already starting the deallocation process.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top