复制对象(二)协议和属性的copy特性

如果要用copy或mutableCopy方法复制自己定义的类对象,那么该类必须要实现<NSCopying>或协议。否则将会导致程序崩溃:

复制对象(二)<NSCopying>协议和属性的copy特性_第1张图片

控制台输出为:

[plain]  view plain copy
  1. 2014-02-01 01:11:09.087 Chocolate[951:303] -[Desserts copyWithZone:]: unrecognized selector sent to instance 0x1001099e0  
  2. 2014-02-01 01:11:09.089 Chocolate[951:303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Desserts copyWithZone:]: unrecognized selector sent to instance 0x1001099e0'  

实现<NSCopying>协议就必须要实现copyWithZone方法,例如B= [A copy],其实现过程为:

首先调用[A copyWithZone:zone];方法创建对象的副本及该对象的引用obj,然后将obj返回并赋值给B。

如果没有实现copyWithZone:方法,copy方法将会发送copyWithZone:nil消息给类,这样将导致程序的崩溃。


如果要复制的类的父类实现了<NSCopying>协议,那么在子类实现复制协议时,必须在copyWithZone方法中首先调用父类的copyWithZone方法。


下面来看个例子:

Desserts类文件

[objc]  view plain copy
  1. #import <Foundation/Foundation.h>  
  2.   
  3. @interface Desserts : NSObject <NSCopying, NSMutableCopying>  
  4.   
  5. @property (strongnonatomicNSMutableString *producer;  
  6.   
  7. @property (assign, nonatomic) NSUInteger price;  
  8.   
  9. - (void)setProducer:(NSMutableString *)theProducer Price:(NSUInteger)thePrice;  
  10.   
  11. @end  
[objc]  view plain copy
  1. #import "Desserts.h"  
  2.   
  3. @implementation Desserts  
  4.   
  5. - (void)setProducer:(NSMutableString *)theProducer Price:(NSUInteger)thePrice {  
  6.     self.producer = theProducer;  
  7.     self.price    = thePrice;  
  8. }  
  9.   
  10. - (NSString *)description {  
  11.     return [NSString stringWithFormat:@"Producer = %@, Price = %lu"self.producerself.price];  
  12. }  
  13.   
  14. - (id)copyWithZone:(NSZone *)zone {  
  15.     Desserts *desserts = [[Desserts allocWithZone:zone] init];  
  16.     desserts.producer  = self.producer;  
  17.     desserts.price     = self.price;  
  18.     return desserts;  
  19. }  
  20.   
  21. - (id)mutableCopyWithZone:(NSZone *)zone {  
  22.     Desserts *desserts = [[Desserts allocWithZone:zone] init];  
  23.     desserts.producer  = self.producer;  
  24.     desserts.price     = self.price;  
  25.     return desserts;  
  26. }  
  27.   
  28. @end  


main.m文件

[objc]  view plain copy
  1. #import <Foundation/Foundation.h>  
  2. #import "Desserts.h"  
  3.   
  4. int main(int argc, const charchar * argv[])  
  5. {  
  6.   
  7.     @autoreleasepool {  
  8.           
  9.         Desserts *desserts = [[Desserts alloc] init];  
  10.         NSMutableString *huizhou = [NSMutableString stringWithString:@"huizhou"];  
  11.         [desserts setProducer:huizhou Price:100];  
  12.           
  13.         Desserts *sweets = [desserts copy];  
  14.           
  15.         [desserts.producer appendString:@" hello factory"];  
  16.         desserts.price++;  
  17.           
  18.         NSLog(@"About desserts:%@", desserts);  
  19.         NSLog(@"About sweets:  %@", sweets);  
  20.           
  21.     }  
  22.     return 0;  
  23. }  

控制台输出:

[plain]  view plain copy
  1. 2014-01-31 17:56:40.178 Chocolate[3093:303] About desserts:Producer = huizhou hello factory, Price = 101  
  2. 2014-01-31 17:56:40.179 Chocolate[3093:303] About sweets:  Producer = huizhou hello factory, Price = 100  


需要特别注意的是,在copy协议中:

[objc]  view plain copy
  1. desserts.producer = self.producer;  
  2. desserts.price    = self.price;  

这里的producer是strong特性的对象,而price是assing特性的基本数据类型变量。

在复制后,sweets和desserts指向两个不同的Desserts对象。

由于price是基本数据类型变量,所以这里的赋值使得sweets和desserts的price属性在内存中是不同的变量。所以desserts.price++并不会对sweets的price造成影响。

由于producer是指针变量,而在copy时,复制成员producer只是简单的赋值,因此desserts.producer和sweets.producer指向同一个NSMutableString对象,故两个对象的producer输出一致。

明显,这并不能达到我们想要的深复制对象内容的目的,因此对于可变对象,应该在复制属性时进行copy操作:

[objc]  view plain copy
  1. //    desserts.producer = self.producer;  
  2.     desserts.producer = [self.producer copy];  

修改后,由于NSMutableString对象的copy是深复制,所以复制后的desserts和sweets指向两个不同的对象:

[plain]  view plain copy
  1. 2014-01-31 18:01:14.803 Chocolate[3106:303] About desserts:Producer = huizhou hello factory, Price = 101  
  2. 2014-01-31 18:01:14.805 Chocolate[3106:303] About sweets:  Producer = huizhou, Price = 100  

对desserts.producer指向的对象的修改并不会影响到sweets.producer指向的对象。

如果属性是不可变对象,如NSString,NSArray等,由于这些对象不可更改,所以我们不用担心这些对象被修改,而且额外的对象会增加内存的开销,所以我们只需要简单的赋值就可以了,而不需要调用copy方法。

对于mutableCopyWithZone方法同理。


实现copyWithZone方法时复制属性小结:

1.基本数据类型的变量复制时直接赋值。

2.对于不可变对象,直接赋值。

3.对于strong特性的对象:如果要求浅复制,直接赋值。如果要求深复制,则要调用copy或mutableCopy方法(当然对于数组或字典来说还是浅复制)。对于copy特性的属性,使用self.property = theProperty会默认调用copy方法进行复制。


下面新建一个Chocolate类,该类继承自Desserts类。如果要实现Chocolate类对象的复制,同样要实现<NSCopying>或<NSMutableCopying>协议中的方法。由于该类继承自Desserts类,所以Chocolate类的copyWithZone方法必须首先调用父类的copyWithZone方法:

[objc]  view plain copy
  1. #import "Desserts.h"  
  2.   
  3. @interface Chocolate : Desserts <NSCopying>  
  4.   
  5. @property (copynonatomicNSMutableString *brand;  
  6.   
  7. @property (strongnonatomicNSString *details;  
  8.   
  9. - (void)setProducer:(NSMutableString *)theProducer  
  10.               Price:(NSUInteger)thePrice  
  11.               Brand:(NSMutableString *)theBrand  
  12.             Details:(NSString *)theDetails;  
  13.   
  14. @end  
[objc]  view plain copy
  1. #import "Chocolate.h"  
  2.   
  3. @implementation Chocolate  
  4.   
  5. - (void)setProducer:(NSMutableString *)theProducer  
  6.               Price:(NSUInteger)thePrice  
  7.               Brand:(NSMutableString *)theBrand  
  8.             Details:(NSString *)theDetails {  
  9.     [super setProducer:theProducer Price:thePrice];  
  10.     self.brand   = theBrand;  
  11.     self.details = theDetails;  
  12. }  
  13.   
  14. - (NSString *)description {  
  15.     return [NSString stringWithFormat:@"\n\tProducer = %@\n\tPrice = %lu\n\tBrand = %@\n\tDetails = %@"self.producerself.priceself.brandself.details];  
  16. }  
  17.   
  18. - (id)copyWithZone:(NSZone *)zone {  
  19.     [super copyWithZone:zone];  
  20.       
  21.     Chocolate *chocolate = [[Chocolate allocWithZone:zone] init];  
  22.     chocolate.producer   = [self.producer copy];  
  23.     chocolate.price      = self.price;  
  24.     chocolate.brand <span style="white-space:pre">  </span> = self.brand;  
  25.     chocolate.details <span style="white-space:pre">    </span> = [self.details copy];  
  26.     return chocolate;  
  27. }  
  28.   
  29. @end  


对于copy特性的属性,与@synthesize一起使用

[objc]  view plain copy
  1. @property (copynonatomicNSMutableString *brand;  

其合成的setter方法会调用copy方法,其实现类似于:

[objc]  view plain copy
  1. - (void)setBrand:(NSMutableString *)theBrand {  
  2.     if (brand != theBrand) {  
  3.         brand = [theBrand copy];  
  4.     }  
  5. }  

由于调用的是copy方法而不是mutableCopy方法,所以创建的是不可变副本,这样就不用担心属性的值被修改,对于copyWithZone方法中的属性变量直接赋值就可以了。

对于可变类型的属性(如NSMutableString,NSMutableArray等),copy特性比strong特性更加安全。而对于不可变对象如NSString,NSArray等,如果赋值源是可变对象,那么也可能会改变NSString的值,如果希望保护该属性不被修改就用copy特性,否则用strong特性。

例如,对于Desserts的producer属性,它是strong特性:

[objc]  view plain copy
  1. @property (strongnonatomicNSMutableString *producer;  
[objc]  view plain copy
  1. Desserts *desserts = [[Desserts alloc] init];  
  2. [desserts setProducer:[NSMutableString stringWithString:@"Huizhou"] Price:100];  
  3. NSMutableString *mstr = desserts.producer;  
  4. NSLog(@"%@", desserts.producer);  
  5.   
  6. [mstr appendString:@" hello factory"];  
  7.   
  8. NSLog(@"%@", desserts.producer);  

控制台输出:

[plain]  view plain copy
  1. 2014-01-31 18:54:07.013 Chocolate[3480:303] Huizhou  
  2. 2014-01-31 18:54:07.015 Chocolate[3480:303] Huizhou hello factory  


以上代码中,将desserts.producer赋值给一个用于临时任务的mstr,并且对mstr进行修改,那么desserts.producer将同样被修改。

如果我们不希望类中的属性被修改,可以将producer的特性改为copy:

[objc]  view plain copy
  1. @property (copynonatomicNSMutableString *producer;  

随后用getter方法获取producer的值并进行修改,将会导致程序崩溃:

[plain]  view plain copy
  1. 2014-01-31 18:56:02.206 Chocolate[3503:303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with appendString:'  

这样可以达到保护属性不被修改的目的。


转载:http://blog.csdn.net/jymn_chen/article/details/18888333

你可能感兴趣的:(复制对象(二)协议和属性的copy特性)