Objective-C 對(duì)象復(fù)制 簡(jiǎn)單實(shí)現(xiàn)
Objective-C 對(duì)象復(fù)制 簡(jiǎn)單實(shí)現(xiàn)是本文要介紹的內(nèi)容,也行對(duì)Objective-C 也不算陌生了,我們先來(lái)看內(nèi)容。
Foundation系統(tǒng)對(duì)象(NSString,NSArray等)
只有遵守NSCopying 協(xié)議的類才可以發(fā)送copy消息
只有遵守 NSMutableCopying 協(xié)議的類才可以發(fā)送mutableCopy消息
copy和mutableCopy區(qū)別就是copy返回后的是不能修改的對(duì)象, 而mutableCopy返回后是可以修改的對(duì)象。
這個(gè)兩個(gè)方法復(fù)制的對(duì)象都需要手動(dòng)釋放。
自義定義Class
自義定Class也需要實(shí)現(xiàn)NSCopying協(xié)義或NSMutableCopying協(xié)議后,其對(duì)象才能提供copy功能。代碼
- //TestProperty.h
 - #import <Cocoa/Cocoa.h>
 - @interface TestProperty : NSObject <NSCopying>{
 - NSString *name; NSString *password;
 - NSMutableString *interest;
 - NSInteger myInt;}@property (retain,nonatomic)
 - NSString *name,*password;
 - @property (retain,nonatomic) NSMutableString *interest;
 - @property NSInteger myInt;
 - -(void) rename:(NSString *)newname;
 - @end//TestProperty.m
 - #import "TestProperty.h"
 - @implementation TestProperty
 - @synthesize name,password,interest;
 - @synthesize myInt;
 - -(void) rename:(NSString *)newname{
 - // 這里可以直接寫成
 - // self.name = newname;
 - // if (name != newname) {
 - [name autorelease];
 - name = newname;
 - [name retain];
 - }
 - }
 - -(void) dealloc{
 - self.name = nil;
 - self.password = nil;
 - self.interest = nil;
 - [super dealloc];}- (id)copyWithZone:(NSZone *)zone{
 - TestProperty *newObj = [[[self class] allocWithZone:zone] init];
 - newObj.name = name;
 - newObj.password = password;
 - newObj.myInt = myInt;
 - //深復(fù)制 NSMutableString *tmpStr = [interest mutableCopy];
 - newObj.interest = tmpStr;
 - [tmpStr release];
 - //淺復(fù)制 //newObj.
 - interestinterest = interest;
 - return newObj;
 - }
 - @end
 
小結(jié):Objective-C 對(duì)象復(fù)制 簡(jiǎn)單實(shí)現(xiàn)的內(nèi)容介紹完,希望本文對(duì)你有所幫助!















 
 
 
 
 
 
 