Skip to content

Instantly share code, notes, and snippets.

@tanb
Last active December 20, 2015 19:08
Show Gist options
  • Save tanb/6180563 to your computer and use it in GitHub Desktop.
Save tanb/6180563 to your computer and use it in GitHub Desktop.
read this article http://objc.tanb.me/issues/nsobject_copy/ (Japanese version only)
NSObject *obj = [NSObject new];
NSObject *copyObj = [obj copy];
NSString *str = @"Hello... Hello... Hello...";
NSString *copyStr = [str copy];
// these are same address.
NSLog(@"%p, %p", str, copyStr);
NSMutableString *mutableStr = [str mutableCopy];
NSString *copyMutableStr = [mutableStr copy];
// these are not same.
NSLog(@"%p, %p", mutableStr, copyMutableStr);
NSString *copyCopyMutableStr = [copyMutableStr copy];
// these are same
NSLog(@"%p, %p", copyMutableStr, copyCopyMutableStr);
NSMutableString *copyMutableStr = [mutableStr copy];
// this raise NSInvalidArgumentException
[copyMutableStr appendString:@"append"];
NSArray *arr = @[@"hello", @"こんにちは"];
NSArray *copyArr = [arr copy];
// these are same
NSLog(@"%p, %p", arr, copyArr);
// contens addresses are same.
NSLog(@"arr's contents");
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%p", obj);
}];
NSLog(@"copyArr's contents");
[copyArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%p", obj);
}];
NSMutableArray *mutableArr = [arr mutableCopy];
// these are not same
NSLog(@"%p, %p", arr, mutableArr);
// but content addresses are same.
NSLog(@"arr's contents");
[arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%p", obj);
}];
NSLog(@"mutableArr's contents");
[mutableArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%p", obj);
}];
NSData *archived = [NSKeyedArchiver archivedDataWithRootObject:arr];
NSArray *deepCopyArr = [NSKeyedUnarchiver unarchiveObjectWithData:archived];
// these are not same
NSLog(@"%p, %p", arr, deepCopyArr);
NSLog(@"deepCopyArr's contents");
[deepCopyArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%p", obj);
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment