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類型的屬性,當對象變化時,屬性值會發(fā)生改變,所以NSString推薦使用copy修飾。(面試重點??) - 深拷貝、淺拷貝的區(qū)別在上面也有體現(xiàn),淺拷貝是拷貝地址,深拷貝是拷貝值。