Objective-C 对象复制

Foundation系统对象(NSString,NSArray等)

只有遵守NSCopying 协议的类才可以发送copy消息
只有遵守 NSMutableCopying 协议的类才可以发送mutableCopy消息

copy和mutableCopy区别就是copy返回后的是不能修改的对象, 而mutableCopy返回后是可以修改的对象。

这个两个方法复制的对象都需要手动释放。

 

自义定义Class

自义定Class也需要实现NSCopying协义或NSMutableCopying协议后,其对象才能提供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;
// 深复制
NSMutableString * tmpStr = [interest mutableCopy];
newObj.interest
= tmpStr;
[tmpStr release];

// 浅复制
// newObj.interest = interest;
return newObj;
}
@end

 

你可能感兴趣的:(Objective-C)