深浅拷贝

NSMutableString * mutStr = [NSMutableString stringWithString:@"hello"];

NSString * strc = [mutStr copy];

NSString * cStrc = [strc copy]; //指针引用

NSMutableString * cmStrc = [strc mutableCopy]; //深拷贝

[cmStrc appendString:@"4555"];

NSMutableString * strM = [mutStr mutableCopy];

[strM appendString:@"123"];

NSMutableArray array = [NSMutableArray arrayWithObjects:@"123",@"345", nil]; NSArray cArray = [array copy];

NSArray * cArray1 = [cArray copy]; //指针引用

NSMutableString * cmArray1 = [cArray mutableCopy]; //深拷

NSMutableArray * mArray = [array mutableCopy];

// [cArray addObject:@"456"]; [mArray addObject:@"456"];

/** //不管是可变的集合还是对象,使用copy和mutableCopy 都是深拷贝 ,但是可变的对象和集合使用copy全部变为不可变,使用mutableCopy还是可变

  • (lldb) p strc (__NSCFString *) $1 = 0x175afa30 @"hello"
  • (lldb) p strM (__NSCFString *) $2 = 0x1766daa0 @"hello"
  • (lldb) p mutStr (__NSCFString *) $3 = 0x175ab560 @"hello"
  • (lldb) p array (__NSArrayM *) $4 = 0x1766dae0 @"2 elements"
  • (lldb) p cArray (__NSArrayI *) $5 = 0x17667100 @"2 elements"
  • (lldb) p mArray (__NSArrayM *) $6 = 0x1766db00 @"2 elements"

但是集合内部的数据还是指针引用

  • (lldb) p array[0] (__NSCFConstantString *) $7 = 0x000d5138 @"123"

  • (lldb) p cArray[0] (__NSCFConstantString *) $9 = 0x000d5138 @"123"

  • (lldb) p mArray[0] (__NSCFConstantString ) $10 = 0x000d5138 @"123"

//对于不可变的对象和集合使用copy全部都是指针引用-->浅拷贝, 为不可变,mutableCopy 都是内容复制 --> 深拷贝,且mutableCopy变为可变

  • (lldb) p strc (__NSCFString *) $5 = 0x1564e8d0 @"hello"
  • (lldb) p cStrc (__NSCFString *) $0 = 0x1564e8d0 @"hello"
  • (lldb) p cmStrc (__NSCFString *) $1 = 0x1564e910 @"hello4555"

  • (lldb) p cArray1 (__NSArrayI *) $2 = 0x1564f7d0 @"2 elements"

  • (lldb) p cmArray1 (NSArrayM *) $3 = 0x1564f8f0 @"2 elements" (lldb) p cArray (NSArrayI ) $4 = 0x1564f7d0 @"2 elements" /

results matching ""

    No results matching ""