__block修饰符与循环引用

来源:互联网 发布:c语言课程设计题目 编辑:程序博客网 时间:2024/06/07 23:21

 主题:__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


0 0