Objective-C 对象复制

本文介绍了Foundation框架中关于对象复制的方法copy和mutableCopy的区别,并通过一个自定义类的实例展示了如何实现NSCopying和NSMutableCopying协议来支持对象的复制操作。

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

 

转载于:https://www.cnblogs.com/pengxl/archive/2010/12/30/1921646.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值