// 1 系统对象的copy 结构都是不可以变 跟调用的对象无关
// 2 系统对象的mutCopy 如果对象是可变 跟调用的对象无关
// NSArray copy 浅复制
// NSDictionary copy 浅复制
// 测试 NSString 的 拷贝
void testNSStringCopy() {
NSString *str1 = @"wang";
NSString *copyStr1 = [str1 copy];
NSMutableString *mutStr2 = [str1 mutableCopy];
[mutStr2 appendString:@"dfafa"];
}
// 测试 NSMutableString 的 拷贝
void testNSMutableStringCopy() {
NSMutableString *mutString = [NSMutableString stringWithString:@"wang"];
NSString *copyString = [mutString copy];
NSMutableString *mutCopyString = [mutString mutableCopy];
// NSMutableString *mutCopyString = mutString;
[mutCopyString appendString:@"zzzzz"];
NSLog(@"original:%@ mutCopyString: %@",mutString, mutCopyString);
}
// 测试 拷贝Array
void testCopyArray () {
NSArray *array = @[@"111",@"222",@"333",[NSMutableString stringWithString:@"WANG"]];
NSLog(@"before %p %@",array,array);
NSArray *copyArray = [array copy];
NSMutableString *indexString = [copyArray lastObject];
[indexString appendString:@"4444"];
NSLog(@"after array %p %@",array,array);
NSLog(@"after copyArray %p %@",copyArray,copyArray);
NSLog(@"%@",copyArray);
}
// 测试 MutableArray 拷贝
void testMutableCopy () {
NSMutableArray *mutArray = [NSMutableArray arrayWithArray:@[@"111",@"222",@"333",[NSMutableString stringWithString:@"wang"]]];
NSLog(@"muArray %p",mutArray);
NSMutableArray *mutCopyArry = [mutArray mutableCopy];
NSMutableString *replaceString = [NSMutableString stringWithString:mutArray[3]];
[mutCopyArry replaceObjectAtIndex:3 withObject:replaceString];
NSLog(@"mutCopArray %p",mutCopyArry);
NSMutableString *mutString = [mutCopyArry lastObject];
[mutString appendString:@"dfasfa"];
NSLog(@"copy 之前的数组最后可变字符串的值:%@",[mutArray lastObject]);
NSLog(@"copy replace 之后可变字符串的值%@",[mutCopyArry lastObject]);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
testNSStringCopy();
NSMutableArray *array=[NSMutableArray arrayWithObjects:@"one",@"two",@"three",@"four",nil];
NSMutableArray *mutableArray=[array mutableCopy];
[mutableArray removeLastObject];
NSLog(@"orginal:%@",array);
NSLog(@"mutCopy:%@",mutableArray);
}
return 0;
}
运行结果
2016-12-23 15:24:05.619 08-系统对象的拷贝[3237:313899] orginal:(
one,
two,
three,
four
)
2016-12-23 15:24:05.620 08-系统对象的拷贝[3237:313899] mutCopy:(
one,
two,
three
)
Program ended with exit code: 0