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); // 一切正常
}
网友评论