平時我們在物件之間傳值多採用 retain(引用計數 +1)的方式。這種做法適用於:當某屬性的值改變時,指向同一記憶體位址的不同指標會一併改變,因為它們本質上指向同一份資料。
但如果需求是「當一個指標所指向的物件屬性改變時,不影響另一個物件」,那麼就必須讓兩者擁有各自獨立的記憶體位址。此時就不能再用 retain,而應改用 copy 關鍵字——因為 copy 在複製時會重新建立一個全新的物件。
以下建立一個 Person 類別來示範。首先是標頭檔,需宣告遵循 NSCopying 協議:
@interface Person : NSObject <NSCopying> {
NSString *name;
NSString *email;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@end
接著是實作檔,重點在於實作 copyWithZone: 方法:
#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,首先類別必須繼承自 NSObject,其次需實作 NSCopying 協議,最後要在類別中實作 - (id)copyWithZone:(NSZone *)zone 方法。若缺少此方法,執行 copy 時程式將直接崩潰,並提示找不到 copyWithZone 方法。
還有一點值得注意:對 NSArray 進行 copy 時,預設是「淺拷貝」,也就是直接將引用計數 +1,陣列內的元素仍指向同一份物件:
NSArray *array1 = [[NSArray alloc] initWithObjects:person1, person2, person3, nil]; NSMutableArray *array2 = [array1 copy]; // 或使用 NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:array1];
如果想要兩個陣列擁有完全獨立的記憶體(即「深拷貝」),則需使用 NSArray 的 initWithArray:copyItems: 並將 copyItems 設為 YES:
NSArray *array1 = [[NSArray alloc] initWithObjects:person1, person2, person3, nil]; NSMutableArray *array2 = [[NSMutableArray alloc] initWithArray:array1 copyItems:YES];
簡言之,retain 讓多個指標共享同一份資料,copy 則建立獨立副本;而針對集合類別,還需進一步區分淺拷貝與深拷貝,才能精準掌控記憶體行為。