一 :简单例子
1.让类实现NSCopying/NSMutableCopying协议。
2.让类实现copyWithZone:/mutableCopyWithZone:方法
@interface Person : NSObject(NSCopying)(因识别问题此处圆括号替换尖括号)
@property (nonatomic, assign) NSInteger age;
@property (nonatomic, copy) NSString *name;
@end
import "Person.h"
@implementation Person
- (id)copyWithZone:(NSZone *)zone {
Person *person = [[[self class] allocWithZone:zone] init];
person.age = self.age;
person.name = self.name;//这里的self就是copy的对象
return person;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
Person *person = NSCopyObject(self, 0, zone);
person.age = self.age;
person.name = self.name;//这里的self就是copy的对象
return person;
}
必须遵守NSCopying,NSMutableCopying协议,不然当Person对象执行copy和mutableCopy时会崩溃!
二 :BaseCopyObject:
#import "BaseCopyObject.h"
@implementation BaseCopyObject
- (id)copyWithZone:(NSZone *)zone{
BaseCopyObject *baseObject = [[self class] allocWithZone:zone];
[self copyOperationWithObject:baseObject];
return baseObject;
}
//子类来主宰赋值操作 重写父类的方法
- (void)copyOperationWithObject:(id)object{
}
@end
#import “Person.h"
@implementation Tools
- (void)copyOperationWithObject:(Person *)object{
object.age = self.age;
}
- (NSString *)description{
return [NSString stringWithFormat:@"<%@ :%p\"age:%ld\">",self.class,self,_age];
}
网友评论