AddressCard类
AddressCard.h
@property (nonatomic,copy)NSString *name;
@property (nonatomic,copy)NSString *number;
- (id)initWithName:(NSString *)name withNumber:(NSString *)number;
AddressCard.m
- (id)initWithName:(NSString *)name withNumber:(NSString *)number{
if(self = [super init])
{
self.name = name;
self.number = number;
}
return self;
}
- (id)copyWithZone:(NSZone *)zone
{
AddressCard *newCard =[ [AddressCard allocWithZone:zone] init];
newCard.name = self.name;
newCard.number = self.number;
return newCard;
}
AddressBook.h
@property (nonatomic,retain)NSMutableArray *Addressbook;
- (id)initWithAddressbook;
AddressBook.m
- (id)initWithAddressbook{
if(self = [super init])
{
self.Addressbook = [[NSMutableArray alloc]init];
}
return self;
}
- (id)copyWithZone:(NSZone *)zone{
AddressBook *book = [[AddressBook allocWithZone:zone] init];
book.Addressbook = self.Addressbook;
return book;
}
main方法实现
int main(int argc, const char * argv[])
{
@autoreleasepool {
NSMutableString *string = [NSMutableString stringWithString:@"yangcw"];
AddressCard *card1 = [[AddressCard alloc]initWithName:string withNumber:@"15007120653"];
AddressCard *card2 = [card1 copy];
NSLog(@"card1=%p,card2 = %p",card1,card2);
NSLog(@"name =%@ number = %@",card1.name,card1.number);
NSLog(@"name =%@ number = %@",card2.name,card2.number);
AddressBook *book = [[AddressBook alloc]initWithAddressbook];
[book.Addressbook addObject:card1];
[book.Addressbook addObject:card2];
AddressBook *book2 = [book copy];
NSLog(@"book1:%p book2:%p",book,book2);
}
return 0;
}
//输出
2014-08-02 09:14:10.751 ycw_0801_3[449:303] card1=0x100102420,card2 = 0x10010c3b0
2014-08-02 09:14:10.753 ycw_0801_3[449:303] name =yangcw number = 15007120653
2014-08-02 09:14:10.754 ycw_0801_3[449:303] name =yangcw number = 15007120653
2014-08-02 09:14:10.754 ycw_0801_3[449:303] book1:0x1005011a0 book2:0x1005013b0
//总结:自定义类实现NSCopying协议,可以实现copy方法
AddressBook.h
@property (nonatomic,retain)NSMutableArray *Addressbook; 为何Addressbook使用属性使用retain,而不是使用copy,因为copy实现的复制是不可变的,所以一旦Addressbook用copy就没有意义了,因为Addressbook是不可变数组,不能添加元素还怎么使用它来增删改查AddressCard