Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2604617
  • 博文数量: 877
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 5920
  • 用 户 组: 普通用户
  • 注册时间: 2013-12-05 12:25
个人简介

技术的乐趣在于分享,欢迎多多交流,多多沟通。

文章分类

全部博文(877)

文章存档

2021年(2)

2016年(20)

2015年(471)

2014年(358)

2013年(26)

分类: iOS平台

2015-09-18 06:55:03

/> 为啥NSString的属性要用copy而不用retain

   之前学习生活中,知道NSString的属性要用copy而不用retain,但是不知道为啥,这两天我研究了一下,然后终于明白了.

具体原因是因为用copy比用retain安全,当是NSString的时候,其实用copy和retain都行,当用NSMutableString,那么就要用copy,NSMutableString的值不会被修改,而用retain的时候,NSMutableString的值会被修改,具体情况,可以看下面的代码:



#import <Foundation/Foundation.h>

//协议有两种方式,第一是以ing结尾形式,第二,以delegate结尾形式
@interface person : NSObject<NSCopying>
@property (nonatomic,copy)NSString * name;

    person * p  = [[person alloc]init];
    
    NSMutableString * name = [[NSMutableString alloc]initWithString:@"hello"];
    p.name = name;
    
    [name appendString:@" word"];
    NSLog(@"%@",p.name);

打印后结果是



2014-07-05 17:08:44.170 DepthCopy[1399:303] hello
Program ended with exit code: 0



我们可以发现打印结果还是hello;

再看下面用retain


#import <Foundation/Foundation.h>

//协议有两种方式,第一是以ing结尾形式,第二,以delegate结尾形式
@interface person : NSObject<NSCopying>

@property (nonatomic,retain)NSString * name;

    person * p  = [[person alloc]init];
    
    NSMutableString * name = [[NSMutableString alloc]initWithString:@"hello"];
    p.name = name;
    
    [name appendString:@" word"];
    NSLog(@"%@",p.name);

打印结果是:
2014-07-05 17:13:19.531 DepthCopy[1412:303] hello word
Program ended with exit code: 0

我们可以发现结果被改变了,成为了hello word;


所以,由以上代码,可以看出copy比retain安全,也就能明白为啥NSString的属性要用copy而不用retain了;

阅读(944) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~