平時在物件之間傳值,我們多半用 retain(引用計數加一)。這種方式適用於「兩個指標指向同一個物件」的情境——因為指向同一個記憶體位址,其中一方的屬性值改變,另一方也會跟著變。
但如果需求是「改動 A 不可影響 B」,就必須讓兩者擁有不同記憶體,這時候 retain 不敷使用,得改用 copy。因為 copy 在複製時會建立一個全新的物件。
Person.h
@interface Person : NSObject <NSCopying>
{
NSString *name;
NSString *email;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@end
Person.m
#import "Person.h"
@implementation Person
@synthesize name, email;
- (id)initWithName:(NSString *)theName andEmail:(NSString *)theEmail {
self = [super init];
if (self) {
self.name = theName;
self.email = theEmail;
}
return self;
}
- (id)copyWithZone:(NSZone *)zone {
Person *aPerson = [[Person allocWithZone:zone] initWithName:[self name]
andEmail:[self email]];
return aPerson;
}
- (void)dealloc {
[name release];
[email release];
[super dealloc];
}
@end
要讓自訂類別支援 copy,有三個必要條件:
NSCopying 協定(注意是 NSCopying,不是 NSCoding,兩者用途不同)。- (id)copyWithZone:(NSZone *)zone。少了第三項,執行 copy 時程式會直接崩潰,並提示找不到 copyWithZone: 方法。
這裡有個容易被忽略的細節:對 NSArray 做 copy,實際上是 retain 式的複製,也就是只把引用計數加一,裡面的元素並沒有被複製。
NSArray *array1 = [[NSArray alloc] initWithObjects:person1, person2, person3, nil]; // 以下兩種寫法效果相同:淺拷貝 NSMutableArray *array2 = [array1 copy]; NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:array1];
若需要元素也被複製(各自擁有不同記憶體),則要使用深拷貝:
NSArray *array1 = [[NSArray alloc] initWithObjects:person1, person2, person3, nil];
// 深拷貝:每個元素都會呼叫 copyWithZone:
NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:array1
copyItems:YES];
實務提醒:copyItems: 是 initWithArray:copyItems: 專用的初始化器,一般 initWithArray: 並沒有這個參數,兩者不可混用。
深拷貝只會複製一層。如果陣列中的元素本身又持有陣列,內層仍會是共享的引用。若真的需要遞迴複製整棵結構,就必須在你的 copyWithZone: 中,對每個容器型別的屬性也呼叫 copy。
另外,NSString、NSNumber、NSValue 這類不可變物件在 copy 時通常會直接回傳自身(retain),因為它們本來就不能被修改,複製沒有意義。這也是為什麼不可變物件的屬性宣告用 copy 或 strong 效果幾乎一樣,但習慣上仍建議用 copy——因為萬一被指派了一個可變子類(例如把 NSMutableString 指派給 NSString 屬性),copy 能確保拿到的是一份不可變快照,避免外部事後修改影響你的物件。
選擇的原則很簡單:需要「各自獨立、互不影響」就用 copy;只是「共享同一份、且確定不會被改動」就用 strong。想清楚物件的所有權語意,比記住 API 更重要。