一 :簡(jiǎn)單例子
1.讓類實(shí)現(xiàn)NSCopying/NSMutableCopying協(xié)議竿报。
2.讓類實(shí)現(xiàn)copyWithZone:/mutableCopyWithZone:方法
@interface Person : NSObject(NSCopying)(因識(shí)別問(wèn)題此處圓括號(hào)替換尖括號(hào))
@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的對(duì)象
return person;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
Person *person = NSCopyObject(self, 0, zone);
person.age = self.age;
person.name = self.name;//這里的self就是copy的對(duì)象
return person;
}
必須遵守NSCopying句携,NSMutableCopying協(xié)議疗锐,不然當(dāng)Person對(duì)象執(zhí)行copy和mutableCopy時(shí)會(huì)崩潰衡载!
二 :BaseCopyObject:
#import "BaseCopyObject.h"
@implementation BaseCopyObject
- (id)copyWithZone:(NSZone *)zone{
BaseCopyObject *baseObject = [[self class] allocWithZone:zone];
[self copyOperationWithObject:baseObject];
return baseObject;
}
//子類來(lái)主宰賦值操作 重寫父類的方法
- (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];
}