ios深拷貝,淺拷貝,拷貝自定義物件的簡單介紹

2021-07-12 05:15:35 字數 2552 閱讀 7215

copy語法的目的:改變副本的時候,不會影響到源物件;

深拷貝:內容拷貝,會產生新的物件。新物件計數器置為1,源物件計數器不變。

淺拷貝:指標拷貝,不會產生新的物件。源物件計數器+1。

拷貝有下面兩個方法實現拷貝:

-(id)copy;  

-(id)mutablecopy;

要實現copy,必須實現協議

陣列,字典,字串都已經實現了協議,以下以字串為例,其他的同理:

1.不可變字串呼叫copy實現拷(淺拷貝)

nsstring *string = [[nsstring alloc] initwithformat:@"abcde"];  

// copy產生的是不可變副本,由於源物件本身就不可變,所以為了效能著想,copy會直接返回源物件本身

// 源物件計數器會+1

// 在淺拷貝情況下,copy其實就相當於retain

nsstring *str = [string copy];

2.不可變字串呼叫mutablecopy實現拷貝,(深拷貝)

nsstring *string = [[nsstring alloc] initwithformat:@"abcd"];  

// 產生了乙個新的物件,計數器為1。源物件的計數器不變。

nsmutablestring *str = [string mutablecopy];//此時存在兩個物件// str:1和// string:1

// str和string不是相同物件

// nslog(@"%i", str == string);//0

nslog(@"string:%@", string);

nslog(@"str:%@", str);

3.可變字串呼叫copy實現拷貝(深拷貝)

nsmutablestring *string = [nsmutablestring stringwithformat:@"age is %i", 10];  

// 會產生乙個新物件,str計數器為1

nsstring *str = [string copy];

4.可變字串的mutablecopy(深拷貝)

nsmutablestring *string = [nsmutablestring stringwithformat:@"age is %i", 10];  

// 會產生乙個新物件,str計數器為1

nsmutablestring *str = [string mutablecopy];

nslog(@"str:%@", str);

nslog(@"string:%@", string);

5.拷貝自定義物件,下面以student物件為例

a.student要實現copy,必須實現協議

b.實現協議的方法:

student.h檔案

@inte***ce

student : nsobject

// copy代表set方法會release舊物件、copy新物件

// 修改外面的變數,並不會影響到內部的成員變數

// 建議:nsstring一般用copy策略,其他物件一般用retain

@property (nonatomic, copy) nsstring *name;

+ (id)studentwithname:(nsstring *)name;

@end

student.m檔案

#import "student.h"

@implementation

student

+ (id)studentwithname:(nsstring *)name

- (void)dealloc

#pragma mark description方法內部不能列印self,不然會造成死迴圈

- (nsstring *)description

#pragma mark copying協議的方法

// 這裡建立的副本物件不要求釋放

- (id)copywithzone:(nszone *)zone

@end

拷貝student

student *stu1 = [student studentwithname:@"stu1"];  

student *stu2 = [stu1 copy];

stu2.name = @"stu2";

nslog(@"stu1:%@", stu1);

nslog(@"stu2:%@", stu2);

[stu2 release];

小結:

建議:nsstring一般用copy策略,其他物件一般用retain;

只有一種情況是淺拷貝:不可變物件呼叫copy方法時,其他情況都為深拷貝;

ios深拷貝,淺拷貝,拷貝自定義物件的簡單介紹

copy語法的目的 改變副本的時候,不會影響到源物件 深拷貝 內容拷貝,會產生新的物件。新物件計數器置為1,源物件計數器不變。淺拷貝 指標拷貝,不會產生新的物件。源物件計數器 1。拷貝有下面兩個方法實現拷貝 objc view plain copy id copy id mutablecopy 要實...

iOS偽拷貝, 淺拷貝, 深拷貝

先來說說偽拷貝。偽拷貝就是生成了乙個指標變數,指向了某乙個物件。接下來我們來 下淺拷貝和深拷貝。首先,從copy開始說,簡而言之,copy的目的就是生成乙個新的例項,然後把其成員都按原例項賦值。對於非指標型的成員,比如bool,int,float,這樣的賦值可以直接進行。但是對於指標型的資料,比如o...

深拷貝,淺拷貝,自定義的類的物件實現拷貝

原來物件型別 拷貝方法 產生的副本物件型別 是否產生了新的物件 拷貝型別 描述nsstring copy nsstring 沒有淺拷貝 因為原來物件不可變,產生的副本也不可變,就沒有必要新申請一塊記憶體去浪費資源,源物件和副本物件就公用一塊記憶體 nsstring nsmutablecopy nsm...