自定义对象|自定义对象 实现 Copy 和 MutableCopy

【自定义对象|自定义对象 实现 Copy 和 MutableCopy】如果是我们定义的对象,那么我们自己要实现NSCopying,NSMutableCopying这样就能调用copymutablecopy了。
举个例子:

@interface MyObj : NSObject { NSMutableString *name; NSString *imutableStr; int age; } @property (nonatomic, retain) NSMutableString *name; @property (nonatomic, retain) NSString *imutableStr; @property (nonatomic) int age; @end @implementation MyObj @synthesize name; @synthesize age; @synthesize imutableStr; - (id)init { if (self = [super init]) { self.name = [[NSMutableString alloc]init]; self.imutableStr = [[NSString alloc]init]; age = -1; } return self; } - (void)dealloc { [name release]; [imutableStr release]; [super dealloc]; } - (id)copyWithZone:(NSZone *)zone { MyObj *copy = [[[self class] allocWithZone:zone] init]; copy.name = [name copy]; copy.imutableStr = [imutableStr copy]; //copy->name = [name copyWithZone:zone]; ; //copy->imutableStr = [name copyWithZone:zone]; // copy->age = age; return copy; } - (id)mutableCopyWithZone:(NSZone *)zone { MutableCopyObject*mutableCopy = [[[self class] alloc] init]; copy.name = [self.name mutableCopy]; copy.age = [imutableStr mutableCopy]; return copy; }

    推荐阅读