iOS 强引用

KCPerson.h


#import 

@interface KCPerson : NSObject

@property (nonatomic,assign) int no;

@end
KCPerson.m


#import "KCPerson.h"

@implementation KCPerson

-(NSString *)description{
    return [NSString stringWithFormat:@"no=%i",_no];
}

@end
main.m


#import 
#import "KCPerson.h"

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        
        //strong
        __strong KCPerson *person1=[[KCPerson alloc]init];
        __strong KCPerson *person2=person1;
        person1.no=1;
        NSLog(@"%@",person2); //结果:no=1
        person1=nil;
        NSLog(@"%@",person2); //结果:no=1
        
        
        //weak
        __strong KCPerson *person3=[[KCPerson alloc]init];
        __weak KCPerson *person4=person3;
        person3.no=3;
        NSLog(@"%@",person4); //结果:no=3
        person3=nil;
        NSLog(@"%@",person4); //结果:(null)

    }
    return 0;
}

由于person1和person2都指向一个对象并且都是强引用,因此当person1设置为nil时对象仍然不会释放,所以此时person2还是指向这个对象,可以正常输出;person3和它指向的对象是强引用,而person4是弱引用,因此当person3设置为nil后,对象没有了强引用就会释放,此时再打印person4自然就是null。为了说明strong和weak的使用,下面使用图形方式描绘上面的情况:

strong–person1和person2的关系

《iOS 强引用》

《iOS 强引用》

由此得出如下结论:

不管是怎么管理内存都是针对对象类型而言(无论是strong,weak都不能应用到基本数据类型),对于基本数据类型直接声明为assign就可以了,它不需要我们自己管理内存;
所有的指针变量默认都是__strong类型,因此我们通常省略不写__strong;
如果一个对象没有强引用之后即使存在弱引用它也会被释放,与此同时弱引用将被设置为nil;

    原文作者:MatTsonga
    原文地址: https://segmentfault.com/a/1190000008915592
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞