2012-03-05 3 views
0

타이머에 대한 cancel_handler가있는 경우 'assign'속성을 사용하여 속성으로 선언 된 ivars를 직접 참조하고 재설정 할 수 있습니까? 아니면 먼저 __block으로 할당해야합니까?dispatch_source_set_cancel_handler 및 @property ivar에 nil 할당

@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); 
} 

답변

0

이바라르를 잘 참조 할 수 있습니다. 그러나 이러한 참조는 self에 대한 암시 적 참조를 포함하므로주기 유지에주의해야합니다. 예를 들어, 직접 ivar을 참조하는 경우 타이머가 종료되지 않으므로 -dealloc에서 타이머를 종료 할 필요가 없습니다.

관련 문제