最近工作事情不多,研究哈深拷贝,浅拷贝。
浅拷贝:浅拷贝是对object对象的指针拷贝,让指针指向同一块内存地址,“对象永远只有一个",浅拷贝使对象的引用计数器+1
深拷贝:深拷贝是对object对象的复制,保留原对象的值,开辟新的内存地址。
1、String的情况
@property (nonatomic, copy) NSString *c_opyString;
@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, weak) NSString *weakString;
//代码
NSString *abc = [NSString stringWithFormat:@"abc"];
NSString *muString = abc.mutableCopy;
self.c_opyString = abc;
self.strongString = abc;
self.weakString = abc;
NSLog(@"\nstring => %p\nmu_string => %p\ncopy_string => %p\nstrong_string => %p\nweak_string => %p", abc, muString, self.c_opyString, self.strongString, self.weakString);
//输出结果
string => 0xa87b931fa2d5b007
mu_string => 0x1005442d0
copy_string => 0xa87b931fa2d5b007
strong_string => 0xa87b931fa2d5b007
weak_string => 0xa87b931fa2d5b007
结果:对String进行copy、strong、weak都是浅拷贝,与原值指向同一块内存。mutableCopy是深拷贝,从新开辟了一块内存。
2、NSMutableString的情况
@property (nonatomic, copy) NSString *c_opyString;
@property (nonatomic, strong) NSString *strongString;
@property (nonatomic, weak) NSString *weakString;
//代码
NSString *muString = abc.mutableCopy;
self.c_opyString = abc;
self.strongString = abc;
self.weakString = abc;
NSLog(@"\nstring => %p\nmu_string => %p\ncopy_string => %p\nstrong_string => %p\nweak_string => %p", abc, muString, self.c_opyString, self.strongString, self.weakString);
//输出结果
string => 0x100506b80
mu_string => 0x1005552b0
copy_string => 0x9c37c6e47ea26229
strong_string => 0x100506b80
weak_string => 0x100506b80
Program ended with exit code: 0
结果:对NSMutableString进行strong、weak都是浅拷贝,与原值指向同一块内存。copy、mutableCopy都是深拷贝,从新开辟了一块内存。
3、Array的情况
@property (nonatomic, copy) NSArray *c_opyArray;
@property (nonatomic, strong) NSArray *strongArray;
@property (nonatomic, weak) NSArray *weakArray;
//代码
NSArray *array = @[@"a", @"b", @"c"];
NSArray *muArray = array.mutableCopy;
self.c_opyArray = array;
self.strongArray = array;
self.weakArray = array;
NSLog(@"\narray => %p\nmu_array => %p\ncopy_array => %p\nstrong_array => %p\nweak_array => %p", array, muArray, self.c_opyArray, self.strongArray, self.weakArray);
//输出结果
array => 0x10052c0c0
mu_array => 0x10052c140
copy_array => 0x10052c0c0
strong_array => 0x10052c0c0
weak_array => 0x10052c0c0
结果:对Array进行copy、strong、weak都是浅拷贝,与原值指向同一块内存。mutableCopy是深拷贝,从新开辟了一块内存。
4、NSMutableArray的情况
@property (nonatomic, copy) NSArray *c_opyArray;
@property (nonatomic, strong) NSArray *strongArray;
@property (nonatomic, weak) NSArray *weakArray;
//代码
NSArray *array = @[@"a", @"b", @"c"];
NSArray *muArray = array.mutableCopy;
self.c_opyArray = array;
self.strongArray = array;
self.weakArray = array;
NSLog(@"\narray => %p\nmu_array => %p\ncopy_array => %p\nstrong_array => %p\nweak_array => %p", array, muArray, self.c_opyArray, self.strongArray, self.weakArray);
//输出结果
array => 0x10073c950
mu_array => 0x10073c7b0
copy_array => 0x10073cc60
strong_array => 0x10073c950
weak_array => 0x10073c950
网友评论