拷貝在 Objective-C 中分為淺拷貝(shallow copy)與深拷貝(deep copy)。兩者的差別在於:拷貝之後新物件與原物件是否共享同一份記憶體。這個差異在處理可變物件時,往往就是 bug 的來源。
NSMutableArray *mArray = [NSMutableArray arrayWithObjects:
[NSMutableString stringWithString:@"origionA"],
[NSMutableString stringWithString:@"origionB"],
[NSMutableString stringWithString:@"origionC"], nil];
NSMutableArray *mArrayCopy = [mArray mutableCopy];
NSMutableString *string = [mArray objectAtIndex:0];
[string appendString:@"Append"];
[mArrayCopy removeObjectAtIndex:1];
NSLog(@"object.name = %@", mArray);
NSLog(@"object.name = %@", mArrayCopy);
輸出結果:
2015-04-23 15:18:15.151 AppTest[14507:122304] object.name = (
origionAAppend,
origionB,
origionC
)
2015-04-23 15:18:15.151 AppTest[14507:122304] object.name = (
origionAAppend,
origionC
)
說明:Foundation 的 copy 與 mutableCopy 只是複製了容器本身,裡面的元素仍然指向同一個物件。所以透過 mArray 取出的 string 做 append,mArrayCopy 中對應的元素也跟著變了。若要產生不可變副本,讓類別遵循 NSCopying;要產生可變副本,則遵循 NSMutableCopying。
@protocol NSCopying - (id)copyWithZone:(NSZone *)zone; @end @protocol NSMutableCopying - (id)mutableCopyWithZone:(NSZone *)zone; @end
自訂類別要支援拷貝,必須實作 NSCopying 或 NSMutableCopying 協議,並在 copyWithZone: 或 mutableCopyWithZone: 中真正建立一個新物件。
@interface DemoObject : NSObject <NSCopying>
@property (strong, nonatomic) NSString *name;
@end
@implementation DemoObject
- (id)copyWithZone:(NSZone *)zone {
DemoObject *object = [[[self class] allocWithZone:zone] init];
return object;
}
@end
拷貝後各自持有獨立物件,改動其中一份不會影響另一份:
NSMutableArray *mArray = [NSMutableArray arrayWithObjects:
[NSMutableString stringWithString:@"origionA"],
[NSMutableString stringWithString:@"origionB"],
[NSMutableString stringWithString:@"origionC"], nil];
NSMutableArray *mArrayCopy = [mArray mutableCopy];
NSMutableString *string = [mArray objectAtIndex:0];
[string appendString:@"Append"];
[mArrayCopy removeObjectAtIndex:1];
NSLog(@"object.name = %@", mArray);
NSLog(@"newObject.name = %@", mArrayCopy);
輸出:
2015-04-23 15:18:15.150 AppTest[14507:122304] object.name = object 2015-04-23 15:18:15.151 AppTest[14507:122304] newObject.name = newObject
關於 zone 參數:它與不同的記憶體分區有關,你可以在程式中自行配置並使用這些分區。只有在撰寫需要配置大量記憶體、且想藉分區來最佳化配置效能的應用時,才需要處理 zone。實務上多數情況直接把它傳給 allocWithZone: 即可。
還有一個容易踩的細節:如果你的自訂類別內部還持有其他物件,copyWithZone: 中必須連那些成員一起做深拷貝,否則只是換了外殼,內部依然是共享的。