1,深拷贝和浅拷贝的区别
浅拷贝:并不拷贝对象本身,仅仅是拷贝指向目标对象的指针,并没有拷贝内容;
深拷贝:直接拷贝整个对象内容到另外一块内存中;
总结一句话: 浅拷贝就是拷贝指针,深拷贝就是拷贝内容。
2,可变类型和非可变类型
非可变类型:NSArray、NSDictionary、NSSet等
可变类型:NSMutableString、NSMutableArray、NSMutableSet等
3,copy和mutableCopy
1.不可变类型,copy结果,不可变(__NSArray0),不产生新对象,浅拷贝;
2.不可变类型,mutableCopy结果,可变(__NSArrayM),产生新对象,深拷贝;
3.可变类型,copy结果,不可变(__NSArray0),产生新对象,深拷贝;
4.可变类型,mutableCopy结果,可变(__NSArrayM),产生新对象,深拷贝;
实例:
OC:
NSArray *arr = [[NSArray alloc] init];
id arr_copy = [arr copy];
id arr_mutableCopy = [arr mutableCopy];
NSLog(@"arr: %p",arr);
NSLog(@"arr_copy: %p",arr_copy);
NSLog(@"arr_mutableCopy: %p",arr_mutableCopy);
NSMutableArray *mutableArr = [[NSMutableArray alloc] init];
id mutableArr_copy = [mutableArr copy];
id mutableArr_mutableCopy = [mutableArr mutableCopy];
NSLog(@"mutableArr: %p",mutableArr);
NSLog(@"mutableArr_copy: %p",mutableArr_copy);
NSLog(@"mutableArr_mutableCopy: %p",mutableArr_mutableCopy);
打印结果:
2019-07-30 09:35:12.128808+0800 OCTest[943:95407] arr: 0x283708090
2019-07-30 09:35:12.128865+0800 OCTest[943:95407] arr_copy: 0x283708090
2019-07-30 09:35:12.128878+0800 OCTest[943:95407] arr_mutableCopy: 0x283b57f90
2019-07-30 09:35:12.128899+0800 OCTest[943:95407] mutableArr: 0x283b57f00
2019-07-30 09:35:12.128915+0800 OCTest[943:95407] mutableArr_copy: 0x283708090
2019-07-30 09:35:12.128928+0800 OCTest[943:95407] mutableArr_mutableCopy: 0x283b57ed0
Swift:
let arr = NSArray.init()
let arr_copy = arr.copy()
let arr_mutableCopy = arr.mutableCopy()
print(String.init(format: "arr: %p", arr))
print(String.init(format: "arr_copy: %p", arr_copy as! CVarArg))
print(String.init(format: "arr_mutableCopy: %p", arr_mutableCopy as! CVarArg))
let mutableArr = NSMutableArray.init()
let mutableArr_copy = mutableArr.copy()
let mutableArr_mutableCopy = mutableArr.mutableCopy()
print(String.init(format: "mutableArr: %p", mutableArr))
print(String.init(format: "mutableArr_copy: %p", mutableArr_copy as! CVarArg))
print(String.init(format: "mutableArr_mutableCopy: %p", mutableArr_mutableCopy as! CVarArg))
打印结果:
arr: 0x280bec070
arr_copy: 0x280bec070
arr_mutableCopy: 0x280781f50
mutableArr: 0x2807826d0
mutableArr_copy: 0x280bec070
mutableArr_mutableCopy: 0x280782700
4,可变与不可变类型重新赋值之后,内存及指针地址变化情况:
一,不可变类型重新赋值
var str = "liang"
//0xdede098284952b23
print(String(format: "%p", str))
str = "lu"
//0xdede0ff46284eb24
print(String(format: "%p", str))
结论:不可变类型重新赋值之后,内存地址改变了。
二,可变类型重新赋值
var string:NSMutableString = "liang"
//0x280946820
print(String(format: "%p", string))
string = "lu"
//0x280946850
print(String(format: "%p", string))
结论:可变类型重新赋值之后,内存地址改变了。
三,可变类型通过append方法改变值
var mutableString:NSMutableString = "liang"
//0x280946820
print(String(format: "%p", mutableString))
mutableString.append("lu")
//0x280946850
print(String(format: "%p", mutableString))
结论:可变类型通过append方法改变值之后,内存地址不变。
补充:通过print("str:(withUnsafePointer(to: &str, {$0}))")方法,打印值改变前后的指针,发现三种情况指针地址均不发生改变。
网友评论