block循环引用的简单说明

- (void)viewDidLoad
{
    [super viewDidLoad];
    // 如果我们不对block进行copy操作, 那么block存在于栈区, 栈区的block块不会对引用的对象进行持有
    // 如果我们对block进行了copy操作, 那么block就存在于堆区, block块就会对引用的对象进行持有
     
    Student *student = [[Student alloc] init];
    // 如何解决循环引用问题
    // 在ARC下
    // 创建一个弱引用对象weakStudent, 可以用__weak修饰, 也可以用__unsafe_unretained来进行修饰
    /*
    __unsafe_unretained typeof(student) weakStudent = student;
    student.testBlock = ^{
        [weakStudent study];
        NSLog(@"111");
    };
     
    student.testBlock();
     */
    /*
    // 在非ARC下我们解决block循环引用的方法
    __block typeof(student) weakStudent = student;
    student.testBlock = ^{
        [weakStudent study];
    };
    student.testBlock();
    [student release];
    */
     
    int age = 10;
    void (^blockA)() = ^{   // 值捕获
        NSLog(@"age == %d", age);
    };
    age = 20;
    blockA();
}
posted @ 2016-05-01 00:36  灬小杰  阅读(104)  评论(0)    收藏  举报