转载自:http://mobile.51cto.com/iphone-277001.htm
Objective-C 对象复制 简单实现是本文要介绍的内容,也行对Objective-C 也不算陌生了,我们先来看内容。
Foundation系统对象(NSString,NSArray等)
只有遵守NSCopying 协议的类才可以发送copy消息
只有遵守 NSMutableCopying 协议的类才可以发送mutableCopy消息
copy和mutableCopy区别就是copy返回后的是不能修改的对象, 而mutableCopy返回后是可以修改的对象。
这个两个方法复制的对象都需要手动释放。
自义定义Class
自义定Class也需要实现NSCopying协义或NSMutableCopying协议后,其对象才能提供copy功能。代码
TestProperty.h//
// TestProperty.h
// HungryBear
//
// Created by Bruce Yang on 12-10-6.
// Copyright (c) 2012年 EricGameStudio. All rights reserved.
//
@interface TestProperty : NSObject <NSCopying> {
NSString* _name;
NSString* _password;
NSMutableString* _interest;
NSInteger _myInt;
}
@property (retain, nonatomic) NSString* name;
@property (retain, nonatomic) NSString* password;
@property (retain, nonatomic) NSMutableString* interest;
@property NSInteger myInt;
@end
TestProperty.mm
//
// TestProperty.mm
// HungryBear
//
// Created by Bruce Yang on 12-10-6.
// Copyright (c) 2012年 EricGameStudio. All rights reserved.
//
#import "TestProperty.h"
@implementation TestProperty
@synthesize name = _name;
@synthesize password = _password;
@synthesize interest = _interest;
@synthesize myInt = _myInt;
-(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;
}
-(void) dealloc {
self.name = nil;
self.password = nil;
self.interest = nil;
[super dealloc];
}
@end
转载于:https://www.cnblogs.com/yang3wei/archive/2012/10/06/2739341.html