Objective-C NSString为什么要用copy修饰而不是strong

Objective-C NSString为什么要用copy修饰而不是strong

看下面代码:

@interface ViewController ()

@property (nonatomic, strong) NSString *strStrong;
@property (nonatomic, copy) NSString *strCopy;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSMutableString *mutableString = [NSMutableString stringWithString:@"hello"];
    self.strStrong = mutableString;
    self.strCopy = mutableString;

    NSLog(@"strStrong:%@",self.strStrong);
    NSLog(@"strCopy:%@",self.strCopy);

    [mutableString appendString:@" world"];
    NSLog(@"strStrong:%@",self.strStrong);
    NSLog(@"strCopy:%@",self.strCopy);
}

先想一下终端会输出什么信息。
下翻看结果

.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.

StringStrongOrCopy[36258:1045977] strStrong:hello
StringStrongOrCopy[36258:1045977] strCopy:hello
StringStrongOrCopy[36258:1045977] strStrong:hello world
StringStrongOrCopy[36258:1045977] strCopy:hello

明白了吗?
当不希望NSString的值被修改时,使用copy会防止不小心修改了NSString的值。

Demo地址

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页