美文网首页
__weak与__unsafe__unretained关键词

__weak与__unsafe__unretained关键词

作者: 传说中的汽水枪 | 来源:发表于2019-06-16 18:45 被阅读0次

    ownership__weak 的使用,对象的生命周期

    - (void)test_weak_ownership {
        id obj1 = [NSObject new];
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-unsafe-retained-assign"
        // 这里会有警告, 用上面的会消除警告
        __weak id obj2 = [NSObject new];
        // obj1 输出正确的结果,obj2输出nil
        NSLog(@"obj1:%@, obj2:%@", obj1, obj2);
    #pragma clang diagnostic pop
    }
    - (void)test_weak_ownership2 {
        id obj1 = [NSObject new];
        __weak id obj2 = obj1;
        NSLog(@"obj2:%@", obj2); // 一切正常
    }
    

    类似的__unsafe__unretained

    - (void)test_unsafe_unretained_ownership {
        id obj1 = [NSObject new];
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-unsafe-retained-assign"
        // 这里会有警告, 用上面的会消除警告
        __unsafe_unretained id obj2 = [NSObject new];
        // obj2 野指针,极大概率会崩溃
        NSLog(@"obj1:%@, obj2:%@", obj1, obj2);
    #pragma clang diagnostic pop
    }
    - (void)test_unsafe_unretained_ownership2 {
        id obj1 = [NSObject new];
        // 这里会有警告, 用上面的会消除警告
        __unsafe_unretained id obj2 = obj1;
        NSLog(@"obj2:%@", obj2); // 一切正常
    }
    

    相关文章

      网友评论

          本文标题:__weak与__unsafe__unretained关键词

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