关闭

ios学习笔记之OC篇(二):引用计数

标签: 引用计数ARC
740人阅读 评论(0) 收藏 举报
分类:
例题:已知存在属性@property (nonatomic,retain) NSArray *arr;该属性自动生成的set方法代码为:
-(void) setArr:(NSArray *)arr
{
     _arr=arr;
     [_arr retain];
}
示例1:
@property (nonatomic,retain) Person *friend;

Person *p=nil;
   
 @autoreleasepool {
       
        //没有添加进自动释放池时,自动释放池对其无影响

        p=[[[
Person alloc]init]autorelease];//+1假如没有autorelease最后一个retainCount仍保持2,不会-1
       
 Person *p1=p;//不变
       
 NSLog(@"%ld",[p retainCount]);
//        Person *p2=[p copy];//p的引用计数不+1
//        NSLog(@"%ld",[p retainCount]);
       
 Person *p3=[[Person alloc]init];
        p3.
friend=p;//p的引用计数+1
       
 NSLog(@"%ld",[p retainCount]);
       
       
 NSLog(@"Hello, World!");
       
    }
//p的引用计数-1
    NSLog(@"%ld",[p retainCount]);
示例2:常量没有引用计数机制,因为永远不能释放这些对象:NSNumber,NSString...也同样适用于使用常量字符串初始化的不可变字符串对象
@autoreleasepool {
//        NSNumber *myInt=[NSNumber numberWithInt:100];  //+1
//        NSNumber *myInt1;  //NSNumber显示不正确
       
 Person *myInt=[[Person alloc]init];
       
 Person *myInt1;
       
 NSMutableArray *myArr=[NSMutableArray array];
       
       
 NSLog(@"myInt retainCount is %ld",[myInt retainCount]);//1
        [myArr
 addObject:myInt];
       
 NSLog(@"after add to array ,myInt retainCount is %ld",(unsigned long)[myInt retainCount]);//2
        myInt1=myInt;
       
 NSLog(@"after assign to myInt1 ,myInt retainCount is %ld",(unsigned long)[myInt retainCount]);//2
        [myInt
 retain];
       
 NSLog(@"after retain ,myInt retainCount is %ld",(unsigned long)[myInt retainCount]);//3
       
 NSLog(@"after retain ,myInt1 retainCount is %ld",(unsigned long)[myInt1 retainCount]);//3
        [myInt
 release];
       
 NSLog(@"after release ,myInt retainCount is %ld",(unsigned long)[myInt retainCount]);//2
        [myArr
 removeObjectAtIndex:0];
       
 NSLog(@"after remove from array,myInt retainCount is %ld",(unsigned long)[myInt retainCount]);//1
    }
示例3:引用计数与实例变量
-(void)setName:(NSString *)_name
{
   
 name=_name;
}
-(
NSString *)name
{
   
 return name;
}

NSMutableString *str3=[NSMutableString stringWithString:@"string 3"];
       
 Person *person =[[Person alloc]init];
       
 NSLog(@"str3 retainCount is %ld",[str3 retainCount]);//1
        [person
 setName:str3];
        NSLog(@"after assign to name ,str3 retainCount is %ld",[str3 retainCount]);//1
ps:假如setName方法的实现为:name=_name;[name retain];则str3的retainCount会+1。
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场