iOS 易忘面試題收集(準備)

來源:互聯網
上載者:User

1、NSString為何要用copy。而不是strong/assign。

案例1:

@interface Test ()  @property (nonatomic, strong) NSString *strongString;  @property (nonatomic, copy) NSString *copyedString;@end@implementation-(void)test{    NSString *string = [NSString stringWithFormat:@"abc"];    self.strongString = string;    self.copyedString = string;    NSLog(@"origin string: %p, %p", string, &string);    NSLog(@"strong string: %p, %p", _strongString, &_strongString);    NSLog(@"copy string: %p, %p", _copyedString, &_copyedString);}@end

結果:

origin string: 0x7fe441592e20, 0x7fff57519a48strong string: 0x7fe441592e20, 0x7fe44159e1f8copy string: 0x7fe441592e20, 0x7fe44159e200

案例2:

@interface Test ()  @property (nonatomic, strong) NSString *strongString;  @property (nonatomic, copy) NSString *copyedString;@end@implementation-(void)test{    NSMutableString *string = [NSMutableString stringWithFormat:@"abc"];    self.strongString = string;    self.copyedString = string;    NSLog(@"origin string: %p, %p", string, &string);    NSLog(@"strong string: %p, %p", _strongString, &_strongString);    NSLog(@"copy string: %p, %p", _copyedString, &_copyedString);    // 是否會有意想不到的事情發生呢    [string appendString:@"333"];    NSLog(@"origin string:%@",  mStr);    NSLog(@"strong string:%@", _rStr);    NSLog(@"copy string:%@",   _cStr);}@end

結果:

origin string: 0x7fe441592e20, 0x7fff57519a48strong string: 0x7fe441592e20, 0x7fe44159e1f8copy string: 0x7fe441592e20, 0x7fe44159e200origin string: abc333strong string: abc333copy string: abc

結論
1. 當來源資料是NSString類型時,使用copy/strong/assign結果是一樣的,都是對對象地址進行拷貝是淺拷貝
2. 當來源資料是NSMutableString類型時,使用copy對象地址改變,是一個新對象,屬於深拷貝。strong/assign地址相同,屬於淺拷貝
3. 所以在修飾string時還是盡量使用copy,避免帶來意想不到的問題。

最後推薦一個自己感覺總結非常好的簡書:https://www.jianshu.com/p/2e1b3f54b4f3

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.