strong,copy有何不同?实践出真知!上代码
strong
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,strong)NSString *name;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSMutableString *string = [[NSMutableString alloc] initWithString:@"张三"];
self.name = string;
NSLog(@"string:%@, 地址:%p", string, string);
NSLog(@"self.name:%@, 地址%p", self.name, self.name);
[string appendString:@"1"];
NSLog(@"string:%@, 地址:%p", string, string);
NSLog(@"self.name:%@, 地址%p", self.name, self.name);
}
@end
运行结果
2021-06-04 22:54:17.867578+0800 iOSDemo[1557:53589] string:张三, 地址:0x6000008aecd0
2021-06-04 22:54:17.867716+0800 iOSDemo[1557:53589] self.name:张三, 地址0x6000008aecd0
2021-06-04 22:54:17.867810+0800 iOSDemo[1557:53589] string:张三1, 地址:0x6000008aecd0
2021-06-04 22:54:17.867893+0800 iOSDemo[1557:53589] self.name:张三1, 地址0x6000008aecd0
copy
//
// ViewController.m
// iOSDemo
//
// Created by 彭之耀 on 2021/6/4.
//
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic,copy)NSString *name;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSMutableString *string = [[NSMutableString alloc] initWithString:@"张三"];
self.name = string;
NSLog(@"string:%@, 地址:%p", string, string);
NSLog(@"self.name:%@, 地址%p", self.name, self.name);
[string appendString:@"1"];
NSLog(@"string:%@, 地址:%p", string, string);
NSLog(@"self.name:%@, 地址%p", self.name, self.name);
}
@end
运行结果
2021-06-04 22:56:08.281057+0800 iOSDemo[1582:54701] string:张三, 地址:0x6000008c5110
2021-06-04 22:56:08.281187+0800 iOSDemo[1582:54701] self.name:张三, 地址0x6000006b6240
2021-06-04 22:56:08.281303+0800 iOSDemo[1582:54701] string:张三1, 地址:0x6000008c5110
2021-06-04 22:56:08.281394+0800 iOSDemo[1582:54701] self.name:张三, 地址0x6000006b6240
分析
- 当我们进行赋值的时候,
strong
是直接将地址值传递给了对象的属性,而copy
是开辟了新的空间,并把值赋值给对象的属性。 -
NSString
类型的属性推荐使用 copy,因为NSMutableString
是NSString
的子类,若将NSMutableString
类型的对象赋值给NSString
类型的属性,当对象变化时,属性值会发生改变,所以NSString
推荐使用copy
修饰。(面试重点) - 深拷贝、浅拷贝的区别在上面也有体现,浅拷贝是拷贝地址,深拷贝是拷贝值。