不是所有的对象都支持 copy
需要继承NSCopying 协议(实现 copyWithZone: 方法)
同样,需要继承NSMutableCopying 协议才可以使用mutableCopy(实现 mutableCopyWithZone: 方法)
默认 NSObject没有实现这两个协议,但是 copy和mutableCopy这两个方法是NSObject定义的
这里要列举范例
//1.h @interface CommonObj
: NSObject < NSCopying > @end @interface MyCObj
: NSObject < NSCopying > @property ( nonatomic , copy )
CommonObj *obj; @end //1.m @implementation CommonObj -
( id )init { self =
[ super init]; if ( self ) { } return self ; } -
( void )dealloc { [ super dealloc]; } -
( id )copyWithZone:( NSZone *)zone { CommonObj
*result = [[[ self class ]
allocWithZone:zone] init]; return result; } @end @implementation MyCObj @synthesize obj
= _obj; -
( id )init { self =
[ super init]; if ( self ) { self ->_obj
= nil ; } return self ; } -
( void )dealloc { if ( self .obj) [ self ->_obj
release]; [ super dealloc]; } -
( id )copyWithZone:( NSZone *)zone { MyCObj
*result = [[[ self class ]
allocWithZone:zone] init]; result->_obj
= [ self ->_obj
copy ]; return result; } @end //main.m -
( void )Test { CommonObj
*a1 = [[CommonObj alloc] init]; CommonObj
*a2 = [a1 copy ]; MyCObj
*b1 = [[MyCObj alloc] init]; MyCObj
*b2 = [b1 copy ]; [b2
release]; [b1
release]; [a2
release]; [a1
release]; } |
打印上述对象的地址,就会发现地址各不相同,retaincount = 1;
这里要注意类似NSString的类,比如:NSArray
NSString *t1 = @"hello";
NSString *t2 = [t1 copy];
打印地址,两个地址一模一样;NSArray对象也是同样。之所以会是同一地址,估计在常量或不可变这个属性上
小结:
这个就是C++下的拷贝构造函数的另类描述,目的在于拷贝。至于实现的拷贝是深度拷贝还是浅度拷贝,这是由实现者设计