解决block循环引用的三种方式



- (void)viewDidLoad {

    [super viewDidLoad];

    self.tools = [[HMNetworkTools alloc ] init];


//    //第三种解决方式

//    //weak-strong-dance wwdc 推出的解决方式  AFN中被大量的运用到

//    __weak typeof(self) weakSelf = self;

//    [self.tools loadData:^(NSString *result) {

//        //闭包中对弱引用的weakSelf 在强引用一下

//        __strong typeof(weakSelf) strongSelf = weakSelf;

//        NSLog(@"%@ %@",result,strongSelf);

//    }];


    

    [self method1];

    

    

}


- (void) method2{

    //解决循环引用的第二种方式

    //会引起 EXC_BAD_ACCESS 错误 MRC 时代最常见的错误  野指针  --> 坏地址访问

    // assgin属性关键字的作用类似  对象被系统回收时 对象的地址不会自动指向nil

    // iOS4.0 block 一起推出的 用来解决循环引用的

    __unsafe_unretained typeof(self) weakSelf = self;

    [self.tools loadData:^(NSString *result) {

        NSLog(@"%@ %@",result,weakSelf);

    }];

}


- (void) method1 {

    //解决循环引用的第一种方式

    //iOS 5.0 引用来解决循环引用的方式  weak属性关键字作用类似

    //当对象被系统回收时  对象的地址 会自动指向 nil  不会出现野指针访问

    __weak typeof(self) weakSelf = self;

    [self.tools loadData:^(NSString *result) {

        NSLog(@"%@ %@",result,weakSelf);

    }];

}

你可能感兴趣的:(其他)