__unsafe_unretained:不会对对象进行retain,当对象销毁时,会依然指向之前的内存空间(野指针)
__weak:不会对对象进行retain,当对象销毁时,会自动指向nil
代码示例
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
Person *p = [[Person alloc] init];
Person *p1 = p;
p = nil;
//p已经指向nil,但是还能访问name属性,说明对象没有被销毁,默认指针被__strong修饰
//__strong Person *p = [[Person alloc] init];
//__strong Person *p1 = p;
NSLog(@"%@",p1);
}
output: <Person: 0x100200000>
- 当使用__weak时
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
Person *p = [[Person alloc] init];
__weak Person *p1 = p
p = nil;
//p指向nil,p1为弱指针,p1指向nil
NSLog(@"%@",p1);
}
- 当使用__unsafe_unretained时
#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
Person *p = [[Person alloc] init];
__unsafe_unretained Person *p1 = p;
p = nil;
//p指向nil,p1的弱引用指针不会销毁,会继续指向对象的地址,对象已经销毁,此时p1访问的是"僵尸"对象
NSLog(@"%@",p1);
}
访问对象已经销毁
-[Person respondsToSelector:]: message sent to deallocated instance 0x100302560
如果喜欢我的文章,可以关注我的微信公众号:沈正方。