您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 深拷貝與淺拷貝:複製的是指標還是記憶體

編輯:iOS 開發綜合

Objective-C 的 copy 是否真的複製一份資料,取決於你在 copyWithZone: 裡怎麼寫。以下用一個 Car 持有 Engine 的簡單模型來對照。

一、淺拷貝:只複製指標

- (id)copyWithZone:(NSZone *)zone {
    Car *car = [[[self class] allocWithZone:zone] init];
    car.engine = _engine;
    car.name   = _name;
    car.weight = _weight;
    return car;
}

測試程式碼:

Car *car = [[Car alloc] init];
Engine *engine = [[Engine alloc] init];
car.engine = engine;
[engine release];

car.name = @"奧迪";
car.weight = @1000;

Car *car2 = [car copy];
NSLog(@"car %@, car2:%@", car.engine, car2.engine);

輸出結果:

car <Engine: 0x100109000>, car2:<Engine: 0x100109000>

兩者的記憶體位址相同,說明淺拷貝只複製了指標,並未配置新的記憶體空間。原物件與拷貝物件共享同一個 Engine 實例,一邊改動,另一邊也跟著變。

二、深拷貝:連內容一起複製

- (id)copyWithZone:(NSZone *)zone {
    Car *car = [[[self class] allocWithZone:zone] init];

    Engine *engineCopy = [[_engine copy] autorelease];
    car.engine = engineCopy;

    NSString *namecopy = [[_name copy] autorelease];
    car.name = namecopy;

    NSNumber *weightcopy = [[_weight copy] autorelease];
    car.weight = weightcopy;

    return car;
}

同樣的測試程式碼,輸出變成:

car <Engine: 0x100107ea0>, car2:<Engine: 0x100108b70>

位址不同,代表開辟了新的空間。程式中的 zone 代表一塊記憶體區域。

這裡有個容易忽略的細節:alloc 時必須用 [self class] 而不是 [Car class] 或 car。若寫死成 Car,當子類別呼叫這個方法去實作 NSCopying 時,就會拿到錯誤的型別,引發記憶體問題。而且子類別繼承父類別時,會一併繼承父類別的屬性與已採用的協議,這個情境遲早會發生。

三、Foundation 類別的預設行為

對不可變物件(如 NSArray)呼叫 copy,預設是淺拷貝,效果相當於 retain:

NSArray *array = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
NSArray *array1 = [array copy];
NSLog(@"%p", array);
NSLog(@"%p", array1);
NSLog(@"the retaincount is %lu", [array retainCount]);

輸出:

0x10010a5d0
0x10010a5d0
the retaincount is 2

位址相同、引用計數增加,這是淺拷貝的特徵。反正物件不可變,共享沒有風險,因此系統直接省下複製成本。

而 mutableCopy 則是不管原物件可不可變,一律做深拷貝:

NSArray *array = [NSArray arrayWithObjects:@"one", @"two", @"three", nil];
NSMutableArray *array1 = [array mutableCopy];
NSLog(@"%p", array);
NSLog(@"%p", array1);
NSLog(@"the retaincount is %lu", [array retainCount]);

輸出:

0x10010a5d0
0x10010b260
the retaincount is 1

位址不同、計數未變,這是深拷貝。注意 mutableCopy 產生的物件所有權屬於你,記得 release 或在 ARC 下交給系統管理。

四、retain:兩個指標指向同一物件

NSMutableArray *array1 = [[NSMutableArray alloc] initWithObjects:
                          @"one", @"two", @"three", @"foure", nil];
NSMutableArray *array2 = [array1 retain];
[array2 removeLastObject];
NSLog(@"%@", array1);
NSLog(@"the retaincount is %ld", array2.retainCount);

結果:

(
    one,
    two,
    three
)
the retaincount is 2

透過 array2 移除元素,array1 看到的內容也跟著改變,因為它們根本是同一個物件。這也說明為什麼「想保護資料不被外部改動」時,retain 是錯的工具,該用 copy。

實務準則: NSString、NSArray、NSDictionary 這類有可變/不可變雙胞胎的類別,其屬性一律宣告為 copy;自訂類別若內部持有其他物件,則視需求在 copyWithZone: 中決定要複製到多深。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved