- #import <Foundation/Foundation.h>
- // 需要用到copy方法的自定义类,需要遵守NSCopying协议,
- // 并实现-(id)copyWithZone:(NSZone *)zone 方法
- @interface User :NSObject<NSCopying>
- {
- NSString *_name;
- }
- + (id)userWithName:(NSString *)name;
- - (void)setName:(NSString *)name;
- @end
- int main(int argc, const char * argv[])
- {
- NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
-
-
- NSString * str= @"who";
- // copy产生inmutable对象,若源对象也是inmutable,则返回同一对象
- NSString * str2=[str copy];
- // mutableCopy都会产生一个新对象,并且是mutable
- NSMutableString * mstr=[str mutableCopy];
- // 源对象为mutable的copy,产生新的inmutable对象
- NSString *str4=[mstr copy];
- NSLog(@"\nstr=%p\nstr2=%p\nmstr=%p\nstr4=%p",str,str2,mstr,str4);
-
-
- User *user1=[User userWithName:mstr];
- [mstr appendString:@" are you"];
- NSLog(@"\nuser1=%@\nmstr=%@",user1,mstr);
-
- // copy后产生新的autorelease过的对象
- User *user2 =[user1 copy];
- [user2 setName:mstr];
- NSLog(@"\nuser1=%@\nuser2=%@",user1,user2);
- [pool drain];
- return 0;
- }
- @implementation User
- + (id)userWithName:(NSString *)name
- {
- id u=[[self alloc] init];
- [u setName:name];
- return [u autorelease];
- }
- - (id)copyWithZone:(NSZone *)zone
- {
- return [User userWithName:self->_name];
- }
- - (void)setName:(NSString *)name
- {
- if(name!=_name)
- {
- [_name release];
- _name=[name copy];
- }
- }
- - (void)dealloc
- {
- NSLog(@"%@ %@ deallocated",[self className],_name);
- [_name release];
- [super dealloc];
- }
- - (NSString *)description
- {
- return [NSString stringWithFormat:@"name is %@",_name];
- }
- @end
复制代码
copy:
NSObject中的对象方法,实为调用[self copyWithZone:nil],此方法在NSCopying协议中声明,
因此需要用到copy的类需要遵守NSCopying协议并实现
-(id)copyWithZone:(NSZone *)zone;方法(zone为OC历史遗留,现基本不用),
系统类的copy方法产生的对象均为inmutable,系统中inmutable对象的copy方法
实现为 :
-(id)copy
{
return [self copyWithZone:nil];
}
-(id)copyWithZone:(NSZone *)zone
{
return [[self retain] autorelease];
}
mutableCopy:
NSObject中的对象方法,实为调用[self mutableCopyWithZone:nil],此方法在NSMutableCopying协议中声明,
因此需要用到mutableCopy的类需要遵守NSMutableCopying协议并实现
-(id)mutableCopyWithZone:(NSZone *)zone;方法,
系统类的mutableCopy方法产生的对象均为mutable,为深复制,产生新对象;
@property 中的copy参数:
与retain都属于内存管理类参数,一般用于OC字符串
(NSString * ,NSMutableString *)与block类型的属性;
手动实现为:
-(void)setXxx:(NSString *)xxx
{
if(_xxx!=xxx)
{
[_xxx release];
_xxx=[xxx copy];
}
}
自定义类实现copy功能:
由于自定义类基本无mutable与inmutable之分,因此实现中一般
无论copy或mutableCopy都为产生新对象,copyWithZone与mutableCopyWithZone
任意实现一个或都实现既可;
一般实现方式(假设User类):
//copy方法一般返回autorelease过的对象
-(id)copyWithZone:(NSZone *)zone
{
User *user = [[User alloc] init];
[user setXxx:[self xxx]];
...
return [user autorelease];
}
|
|