美文网首页
OC中解决循环引用的两种方法

OC中解决循环引用的两种方法

作者: oh_flying | 来源:发表于2017-05-25 10:49 被阅读52次

    直接看代码,大概就是这样子:

    @interface DemoViewController ()
    @property (nonatomic,copy)void (^completionCallBack)();
    @end
    
    @implementation DemoViewController
    
    - (void)viewDidLoad {
    [super viewDidLoad];
    
         //解除引用1:__weak
     //    __weak typeof(self) weakSelf = self;
    //    [self loadData:^{
    //        NSLog(@"%@",weakSelf.view);
    //    }];
    
    //解除引用2:__unsafe_unretained
    __unsafe_unretained typeof(self) weakSelf = self;
    //__unsafe_unretained同样是assign的引用(mrc中没有weak)
    //在mrc中如果要弱引用对象都是assign,不会增加引用计数,但是对象一旦被释放,地址不会改变,继续访问,出现野指针
    //在arc weak,本质上是一个观察者模式,一旦发现对象被释放,自动将地址设置为nil,更加安全
    //效率 weak会略微差一些
    [self loadData:^{
        NSLog(@"%@",weakSelf.view);
    }];
    
    // Do any additional setup after loading the view.
    }
    
    - (void)loadData:(void (^)())completion{
    //使用属性记录block
    self.completionCallBack = completion;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSLog(@"耗时操作%@",[NSThread currentThread]);
        [NSThread sleepForTimeInterval:2.0];
        dispatch_async(dispatch_get_main_queue(), ^{
            //执行block
            completion();
        });
    });
    }
    

    这个就是OC中解决循环引用的两种方式。

    相关文章

      网友评论

          本文标题:OC中解决循环引用的两种方法

          本文链接:https://www.haomeiwen.com/subject/kiiaxxtx.html