0

当您有一个计时器的取消处理程序时,您可以直接引用和重置任何声明为具有“分配”属性的属性的 ivars,还是必须首先将其分配为 __block?

@interface SomeClass: NSObject { }
@property (nonatomic, assign) dispatch_source_t             timer;
@end

// Class implementation
@implementation SomeClass

@synthesize timer = _timer;
- (void)startTimer 
{
    dispatch_queue_t globalQ = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    self.timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 
                                    0, 0, globalQ); 

    dispatch_time_t startWhen = dispatch_walltime(DISPATCH_TIME_NOW, NSEC_PER_SEC * 1);
    dispatch_source_set_timer(_timer, startWhen, 1 * NSEC_PER_SEC, 5000ull);

    dispatch_source_set_event_handler(_timer, ^{
        // timer's event handler    
    });

    // VERSION 1:
    // Is it okay to reference and assign self.timer to nil 
    // or does it have to be declared as __block as in VERSION 2?
    dispatch_source_set_cancel_handler(_timer, ^{
        dispatch_release(_timer);                
        self.timer = nil;
    });


    // VERSION 2:
    __block myTimer = self.timer;
    dispatch_source_set_cancel_handler(_timer, ^{
        dispatch_release(myTimer);        

        myTimer = nil;
    });

    dispatch_resume(_timer);
}
4

1 回答 1

0

你可以参考 ivars 就好了。但是,这些引用带有对 的隐式引用self,因此您需要警惕保留循环。例如,如果您直接引用 ivar,则不要期望关闭计时器,-dealloc因为它永远不会被调用。

于 2012-03-05T20:02:40.827 回答