為啥NSString的屬性要用copy而不用retain

來源:互聯網
上載者:User

為啥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] helloProgram 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 wordProgram ended with exit code: 0

我們可以發現結果被改變了,成為了hello word;

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.