__unsafe_unretained:不會(huì)對對象進(jìn)行retain亡鼠,當(dāng)對象銷毀時(shí)涤垫,會(huì)依然指向之前的內(nèi)存空間(野指針)
__weak:不會(huì)對對象進(jìn)行retain,當(dāng)對象銷毀時(shí),會(huì)自動(dòng)指向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已經(jīng)指向nil,但是還能訪問name屬性,說明對象沒有被銷毀溯街,默認(rèn)指針被__strong修飾
//__strong Person *p = [[Person alloc] init];
//__strong Person *p1 = p;
NSLog(@"%@",p1);
}
output: <Person: 0x100200000>
- 當(dāng)使用__weak時(shí)
#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);
}
- 當(dāng)使用__unsafe_unretained時(shí)
#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的弱引用指針不會(huì)銷毀,會(huì)繼續(xù)指向?qū)ο蟮牡刂?對象已經(jīng)銷毀,此時(shí)p1訪問的是"僵尸"對象
NSLog(@"%@",p1);
}
訪問對象已經(jīng)銷毀
-[Person respondsToSelector:]: message sent to deallocated instance 0x100302560
如果喜歡我的文章洋丐,可以關(guān)注我的微信公眾號:沈正方呈昔。