ObjectiveC 深浅拷贝学习
(轉(zhuǎn)自 http://woshao.com/article/f91898b24a1211e097d3000c2959fd2a/)
在ObjC中,什么是深淺拷貝?
深淺拷貝分別指深拷貝和淺拷貝,即mutableCopy和copy方法。
copy復(fù)制一個(gè)不可變對(duì)象,而mutableCopy復(fù)制一個(gè)mutable可變對(duì)象。
什么時(shí)候用到深淺拷貝?下面舉幾個(gè)例子說(shuō)明。
非容器類(lèi)對(duì)象
如NSString,NSNumber等一類(lèi)對(duì)象
示例1:
| 1 2 3 4 5 | // 非容器類(lèi)對(duì)象 ? ??NSString?*str?=?@"origin string"; ? ??NSString?*strCopy?=?[str copy]; ? ??NSMutableString?*mstrCopy?=?[str mutableCopy]; ? ??[mstrCopy appendString:@"??"]; |
查看內(nèi)存可以發(fā)現(xiàn),str和strCopy指向的是同一塊內(nèi)存區(qū)域,我們稱(chēng)之為弱引用(weak reference)。而mstrCopy是真正的復(fù)制,系統(tǒng)為其分配了新內(nèi)存空間,保存從str復(fù)制過(guò)來(lái)的字符串值。從最后一行代碼中修改這些值而不影 響str和strCopy中可證明。
示例2:
| 1 2 3 4 5 6 7 | NSMutableString?*mstr?=?[NSMutableString?stringWithString:@"origin"]; ? ??NSString?*strCopy?=?[mstr copy]; ? ??NSMutableString?*mstrCopy?=?[mstr copy]; ? ??NSMutableString?*mstrMCopy?=?[mstr mutableCopy]; ? ??//[mstrCopy appendString:@"1111"]; ?//error ? ??[mstr appendString:@"222"]; ? ??[mstrMCopy appendString:@"333"]; |
以上四個(gè)對(duì)象所分配的內(nèi)存都是不一樣的。而且對(duì)于mstrCopy,它所指向的其實(shí)是一個(gè)imutable對(duì)象,是不可改變的,所以會(huì)出錯(cuò)。這點(diǎn)要注意,好好理解。
小結(jié):
對(duì)于非容器類(lèi)對(duì)象,有:
- 如果對(duì)一個(gè)不可變對(duì)象復(fù)制,copy是指針復(fù)制,即淺拷貝;而mutableCopy則是對(duì)象復(fù)制,即深拷貝。(示例1)
- 如果是對(duì)可變對(duì)象復(fù)制,都是深拷貝,但copy復(fù)制返回的對(duì)象是不可變的。(示例2)
容器類(lèi)對(duì)象深淺復(fù)制
比如NSArray,NSDictionary等。對(duì)于容器類(lèi)本身,上面討論的結(jié)論也適用的,下面探討的是復(fù)制后容器內(nèi)對(duì)象的變化。
示例3
| 1 2 3 4 5 6 7 8 9 10 11 12 | /* copy返回不可變對(duì)象,mutablecopy返回可變對(duì)象 */ ? ?? ? ??NSArray?*array1 ? ??=?[NSArray?arrayWithObjects:@"a",@"b",@"c",nil]; ? ??NSArray?*arrayCopy1?=?[array1 copy]; ? ??//arrayCopy1是和array同一個(gè)NSArray對(duì)象(指向相同的對(duì)象),包括array里面的元素也是指向相同的指針 ? ? NSLog(@"array1 retain count: %d",[array1 retainCount]); ? ? NSLog(@"array1 retain count: %d",[arrayCopy1 retainCount]); ? ?? ? ??NSMutableArray?*mArrayCopy1?=?[array1 mutableCopy]; ? ??//mArrayCopy1是array1的可變副本,指向的對(duì)象和array1不同,但是其中的元素和array1中的元素指向的還是同一個(gè)對(duì)象。mArrayCopy1還可以修改自己的對(duì)象 ? ??[mArrayCopy1 addObject:@"de"]; ? ??[mArrayCopy1 removeObjectAtIndex:0]; |
array1和arrayCopy1是指針復(fù)制,而mArrayCopy1是對(duì)象復(fù)制,符合前面示例1討論的結(jié)論。mArrayCopy1可以改變其內(nèi)的元素:刪除或添加。但容器內(nèi)的元素內(nèi)容都是淺拷貝。
示例4
| 1 2 3 4 5 6 7 8 9 10 11 12 13 | NSArray?*mArray1?=?[NSArray?arrayWithObjects:[NSMutableString?stringWithString:@"a"],@"b",@"c",nil]; ? ? NSLog(@"mArray1 retain count: %d",[mArray1 retainCount]); ? ??NSArray?*mArrayCopy2?=?[mArray1 copy]; ? ? NSLog(@"mArray1 retain count: %d",[mArray1 retainCount]); ? ??// mArray1和mArrayCopy2指向同一對(duì)象,retain值+1。 ? ?? ? ??NSMutableArray?*mArrayMCopy1?=?[mArray1 mutableCopy]; ? ? NSLog(@"mArray1 retain count: %d",[mArray1 retainCount]); ? ??//mArrayCopy2和mArray1指向的是不一樣的對(duì)象,但是其中的元素都是一樣的對(duì)象——同一個(gè)指針 ? ??NSMutableString?*testString?=?[mArray1 objectAtIndex:0]; ? ??//testString = @"1a1";//這樣會(huì)改變testString的指針,其實(shí)是將@“1a1”臨時(shí)對(duì)象賦給了testString ? ??[testString appendString:@" tail"];//這樣以上三個(gè)數(shù)組的首元素都被改變了 |
由此可見(jiàn),對(duì)于容器而言,其元素對(duì)象始終是指針復(fù)制。如果需要元素對(duì)象也是對(duì)象復(fù)制,就需要實(shí)現(xiàn)深拷貝。http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Copying.html
示例5
| 1 2 3 4 | NSArray?*array?=?[NSArray?arrayWithObjects:[NSMutableString?stringWithString:@"first"],[NSStringstringWithString:@"b"],@"c",nil]; ? ??NSArray?*deepCopyArray=[[NSArray?alloc]?initWithArray:?array copyItems:?YES]; ? ??NSArray*?trueDeepCopyArray?=?[NSKeyedUnarchiver?unarchiveObjectWithData: ? ??[NSKeyedArchiver?archivedDataWithRootObject:?array]]; |
trueDeepCopyArray是完全意義上的深拷貝,而deepCopyArray則不是,對(duì)于deepCopyArray內(nèi)的不可變?cè)仄溥€是指針復(fù)制。
或者我們自己實(shí)現(xiàn)深拷貝的方法。因?yàn)槿绻萜鞯哪骋辉厥遣豢勺兊?#xff0c;那你復(fù)制完后該對(duì)象仍舊是不能改變的,因此只需要指針復(fù)制即可。除非你對(duì)容器內(nèi)的元素重新賦值,否則指針復(fù)制即已足夠。
舉個(gè)例子,[[array objectAtIndex:0]appendstring:@”sd”]后其他的容器內(nèi)對(duì)象并不會(huì)受影響。[[array objectAtIndex:1]和[[deepCopyArray objectAtIndex:0]盡管是指向同一塊內(nèi)存,但是我們沒(méi)有辦法對(duì)其進(jìn)行修改——因?yàn)樗遣豢筛淖兊摹K灾羔槒?fù)制已經(jīng)足夠。所以這并不是完全 意義上的深拷貝。
自己實(shí)現(xiàn)深拷貝的方法
NSDictionaryMutableDeepCopy.h
| 1 2 3 4 5 6 7 8 | #import <foundation /Foundation.h> @interface?NSDictionary(MutableDeepCopy) -?(NSMutableDictionary?*)mutableDeepCopy; @end </foundation> |
NSDictionaryMutableDeepCopy.m
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #import "NSDictionaryMutableDeepCopy.h" @implementation?NSDictionary(MutableDeepCopy) -?(NSMutableDictionary?*)mutableDeepCopy?{ ? ??NSMutableDictionary?*ret?=?[[NSMutableDictionary?alloc] ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? initWithCapacity:[self count]]; ? ??NSArray?*keys?=?[self allKeys]; ? ??for?(id?key?in?keys)?{ ? ? ? ??id?oneValue?=?[self valueForKey:key]; ? ? ? ??id?oneCopy?=?nil; ? ? ? ?? ? ? ? ??if?([oneValue respondsToSelector:@selector(mutableDeepCopy)])?{ ? ? ? ? ? ? oneCopy?=?[oneValue mutableDeepCopy]; ? ? ? ??} ? ? ? ??else?if?([oneValue respondsToSelector:@selector(mutableCopy)])?{ ? ? ? ? ? ? oneCopy?=?[oneValue mutableCopy]; ? ? ? ??} ? ? ? ??if?(oneCopy?==?nil)?{ ? ? ? ? ? ? oneCopy?=?[oneValue copy]; ? ? ? ??} ? ? ? ??[ret setValue:oneCopy forKey:key]; ? ??} ? ?? ? ??return?ret; } @end |
使用類(lèi)別方法來(lái)實(shí)現(xiàn)。
自定義對(duì)象
如果是我們定義的對(duì)象,那么我們自己要實(shí)現(xiàn)NSCopying,NSMutableCopying這樣就能調(diào)用copy和mutablecopy了。舉個(gè)例子:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 5 | @interface?MyObj?:?NSObject<nscopying ,NSMutableCopying> { ? ? ? ? ?NSMutableString?*name; ? ? ? ? ?NSString?*imutableStr; ? ? ? ? ?int?age; } @property?(nonatomic, retain)?NSMutableString?*name; @property?(nonatomic, retain)?NSString?*imutableStr; @property?(nonatomic)?int?age; ? @end ? @implementation?MyObj @synthesize?name; @synthesize?age; @synthesize?imutableStr; -?(id)init { ? ? ? ? ?if?(self?=?[super init]) ? ? ? ? ?{ ? ? ? ? ? ? ? ? ? ?self.name?=?[[NSMutableString?alloc]init]; ? ? ? ? ? ? ? ? ? ?self.imutableStr?=?[[NSString?alloc]init]; ? ? ? ? ? ? ? ? ? ?age?=?-1; ? ? ? ? ?} ? ? ? ? ?return?self; } ? -?(void)dealloc { ? ? ? ? ?[name release]; ? ? ? ? ?[imutableStr release]; ? ? ? ? ?[super dealloc]; } -?(id)copyWithZone:(NSZone?*)zone { ? ? ? ? ?MyObj?*copy?=?[[[self class]?allocWithZone:zone]?init]; ? ? ? ? ?copy->name?=?[name copy]; ? ? ? ? ?copy->imutableStr?=?[imutableStr copy]; // ? ? ? copy->name = [name copyWithZone:zone];; // ? ? ? copy->imutableStr = [name copyWithZone:zone];// ? ? ? ? ?copy->age?=?age; ? ? ? ? ? ?return?copy; } -?(id)mutableCopyWithZone:(NSZone?*)zone { ? ? ? ? ?MyObj?*copy?=?NSCopyObject(self,?0, zone); ? ? ? ? ?copy->name?=?[self.name mutableCopy]; ? ? ? ? ?copy->age?=?age; ? ? ? ? ?return?copy; } @end </nscopying |
本文參考了on my way的《ios 深淺拷貝學(xué)習(xí)》
?
?
文章來(lái)源:http://donbe.blog.163.com/blog/static/13804802120103272343790/
原來(lái)不是所有的對(duì)象都支持 copy
只有遵守NSCopying 協(xié)議的類(lèi)才可以發(fā)送copy消息
只有遵守 NSMutableCopying 協(xié)議的類(lèi)才可以發(fā)送mutableCopy消息
假如發(fā)送了一個(gè)沒(méi)有遵守上訴兩協(xié)議而發(fā)送 copy或者 mutableCopy,那么就會(huì)發(fā)生異常
默認(rèn) nsobject沒(méi)有遵守這兩個(gè)協(xié)議
但是 copy和mutableCopy這兩個(gè)方法是nsobject定義的
如果想自定義一下copy 那么就必須遵守NSCopying,并且實(shí)現(xiàn) copyWithZone: 方法
如果想自定義一下mutableCopy 那么就必須遵守NSMutableCopying,并且實(shí)現(xiàn) mutableCopyWithZone: 方法
看了一下幾個(gè)遵守 NSCopying協(xié)議的基本上是一些基礎(chǔ)核心類(lèi)
比如 NSString NSNumber
copy以后,就是返回一個(gè)新的類(lèi), 你要負(fù)責(zé)釋放掉,原先被拷貝的retaincount沒(méi)有+1 所以,不需要負(fù)責(zé)釋放
copy和mutableCopy 就是copy返回后的是不能修改的對(duì)象, mutableCopy返回后是可以修改的對(duì)象
下面是實(shí)現(xiàn)一個(gè)copyWithZone的例子
@interface BankAccount: NSObject <NSCopying>
{
double accountBalance;
long accountNumber;
}
-(void) setAccount: (long) y andBalance: (double) x;
-(double) getAccountBalance;
-(long) getAccountNumber;
-(void) setAccountBalance: (double) x;
-(void) setAccountNumber: (long) y;
-(void) displayAccountInfo;
-(id) copyWithZone: (NSZone *) zone;
@end
-(id) copyWithZone: (NSZone *) zone
{
BankAccount *accountCopy = [[BankAccount allocWithZone: zone] init];
[accountCopy setAccount: accountNumber andBalance: accountBalance];
return accountCopy;
}
深度拷貝和淺拷貝
上面的方法是淺拷貝,意思就是,只是重新分配了BankAccount類(lèi)的 內(nèi)存,并沒(méi)有對(duì)BankAccount的屬性重新分配內(nèi)存
兩個(gè)BankAccount的屬性都是指向同一個(gè)地方的. 修改了其中一個(gè)BankAccount屬性,那么另外一個(gè)BankAccount屬性
也會(huì)一起發(fā)生變化?
深度拷貝
深度拷 貝這里用到一個(gè)存檔功能,先把原先的存檔(其實(shí)就是序列化對(duì)象,然后存到一個(gè)文件,等下可以反序列化出來(lái)賦值給另外一個(gè)對(duì)象),然后存到另外的而一個(gè)對(duì)象 中
NSKeyedArchiver 序列化類(lèi)
NSKeyedUnarchiver 反序列化類(lèi)
NSArray *myArray1;
NSArray *myArray2;
NSMutableString *tmpStr;
NSMutableString *string1;
NSMutableString *string2;
NSMutableString *string3;
NSData *buffer;
string1 = [NSMutableString stringWithString: @"Red"];
string2 = [NSMutableString stringWithString: @"Green"];
string3 = [NSMutableString stringWithString: @"Blue"];
myArray1 = [NSMutableArray arrayWithObjects: string1, string2, string3, nil];
buffer = [NSKeyedArchiver archivedDataWithRootObject: myArray1];
myArray2 = [NSKeyedUnarchiver unarchiveObjectWithData: buffer];
tmpStr = [myArray1 objectAtIndex: 0];
[tmpStr setString: @"Yellow"];
NSLog (@"First element of myArray1 = %@", [myArray1 objectAtIndex: 0]);
NSLog (@"First element of myArray2 = %@", [myArray2 objectAtIndex: 0]);
cocoa 的屬性也有3種
protected - Access is allowed on
private - Access is restricted to methods of the class. Access is not available to subclasses.?
public - Direct access available to methods of the class, subclasses and code in other module files and classes.
public的變量可以用 -> 操作符訪問(wèn)
參 考地址:http://www.techotopia.com/index.php/Copying_Objects_in_Objective-C
http://wenku.baidu.com/view/12d6592fb4daa58da0114af0.html
http://www.techotopia.com/index.php/Objective-C_-_Data_Encapsulation,_Synthesized_Accessors_and_Dot_Notation
關(guān) 于訪問(wèn)器的詳細(xì)文檔
http://cocoacast.com/?q=node/103
轉(zhuǎn)載于:https://www.cnblogs.com/pengyingh/articles/2352908.html
總結(jié)
以上是生活随笔為你收集整理的ObjectiveC 深浅拷贝学习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: SQL SERVER2000存储过程调试
- 下一篇: port wifi to ICS(4.0