__block修飾符與循環引用

 主題:__block修飾符
 參考:
 用途:
 當閉包中使用外部self或其局部變量時,需要對其進行__block修飾符。否則,會產生循環引用。
 
 注意事項:
 1 使用前,判斷是否爲空指針。空指針會導致崩潰。
 2 self要用__weak修飾
 3 使用後,要置於空,解除引用
 
 
 相關概念:
 何爲“循環引用”,有何影響?
 A持有B,B持有A。會導致AB的引用計數永遠不爲0.造成內存泄露,甚至崩潰。
 
 委託爲何用weak?
 weak是指某對象A的弱引用B,如果A被銷燬,自動置nil。對nil發送小心,不會崩潰。
 若採用assign,B僅是A的指針。A被銷燬,再對B發消息,相當於對不存在的對象發消息,可能崩潰。
 
 dealloc何時調用?
 引用計數爲0時。



#import "BlockFunction.h"

@interface TestDealloc : NSObject{
    NSTimer *timer;
}

@end

@implementation TestDealloc

-(void) testNSTimer{
    
    timer=[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(runTimer) userInfo:nil repeats:1];
}

/*
 外部,若不主動調用。
 timer會處於validate狀態,引用計數不爲0.
 導致外部一直等待。
 
 參考網址:http://www.cnblogs.com/wengzilin/p/4347974.html
 */
-(void) cleanTimer{
    
    [timer invalidate];
    timer  = nil;
}

-(void) runTimer{

    NSLog(@"runTimer running");
}

/*
 retainCount爲0時,才調用。若發生循環引用,則不會調用。
 */
-(void) dealloc{
    
    NSLog(@"TestDealloc dealloc");
}

@end

#pragma mark-

@interface BlockFunction()

@end

@implementation BlockFunction


#pragma mark-

-(void) test{

    TestDealloc *testDealloc = [TestDealloc alloc];
    [testDealloc testNSTimer];
    [testDealloc cleanTimer]; //關鍵的,如果不調用,則會造成循環引用。dealloc運行無效,需顯示調用。

}

@end


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章