複製對象(二)<NSCopying>協議和屬性的copy特性

來源:互聯網
上載者:User

如果要用copy或mutableCopy方法複製自己定義的類對象,那麼該類必須要實現<NSCopying>或協議。否則將會導致程式崩潰:



控制台輸出為:

2014-02-01 01:11:09.087 Chocolate[951:303] -[Desserts copyWithZone:]: unrecognized selector sent to instance 0x1001099e02014-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類檔案

#import <Foundation/Foundation.h>@interface Desserts : NSObject <NSCopying, NSMutableCopying>@property (strong, nonatomic) NSMutableString *producer;@property (assign, nonatomic) NSUInteger price;- (void)setProducer:(NSMutableString *)theProducer Price:(NSUInteger)thePrice;@end
#import "Desserts.h"@implementation Desserts- (void)setProducer:(NSMutableString *)theProducer Price:(NSUInteger)thePrice {    self.producer = theProducer;    self.price    = thePrice;}- (NSString *)description {    return [NSString stringWithFormat:@"Producer = %@, Price = %lu", self.producer, self.price];}- (id)copyWithZone:(NSZone *)zone {    Desserts *desserts = [[Desserts allocWithZone:zone] init];    desserts.producer  = self.producer;    desserts.price     = self.price;    return desserts;}- (id)mutableCopyWithZone:(NSZone *)zone {    Desserts *desserts = [[Desserts allocWithZone:zone] init];    desserts.producer  = self.producer;    desserts.price     = self.price;    return desserts;}@end


main.m檔案

#import <Foundation/Foundation.h>#import "Desserts.h"int main(int argc, const char * argv[]){    @autoreleasepool {                Desserts *desserts = [[Desserts alloc] init];        NSMutableString *huizhou = [NSMutableString stringWithString:@"huizhou"];        [desserts setProducer:huizhou Price:100];                Desserts *sweets = [desserts copy];                [desserts.producer appendString:@" hello factory"];        desserts.price++;                NSLog(@"About desserts:%@", desserts);        NSLog(@"About sweets:  %@", sweets);            }    return 0;}

控制台輸出:

2014-01-31 17:56:40.178 Chocolate[3093:303] About desserts:Producer = huizhou hello factory, Price = 1012014-01-31 17:56:40.179 Chocolate[3093:303] About sweets:  Producer = huizhou hello factory, Price = 100


需要特別注意的是,在copy協議中:

desserts.producer = self.producer;desserts.price    = self.price;

這裡的producer是strong特性的對象,而price是assing特性的基礎資料型別 (Elementary Data Type)變數。

在複製後,sweets和desserts指向兩個不同的Desserts對象。

由於price是基礎資料型別 (Elementary Data Type)變數,所以這裡的賦值使得sweets和desserts的price屬性在記憶體中是不同的變數。所以desserts.price++並不會對sweets的price造成影響。

由於producer是指標變數,而在copy時,複製成員producer只是簡單的賦值,因此desserts.producer和sweets.producer指向同一個NSMutableString對象,故兩個對象的producer輸出一致。

明顯,這並不能達到我們想要的深複製對象內容的目的,因此對於可變對象,應該在複製屬性時進行copy操作:

//    desserts.producer = self.producer;    desserts.producer = [self.producer copy];

修改後,由於NSMutableString對象的copy是深複製,所以複製後的desserts和sweets指向兩個不同的對象:

2014-01-31 18:01:14.803 Chocolate[3106:303] About desserts:Producer = huizhou hello factory, Price = 1012014-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.基礎資料型別 (Elementary Data Type)的變數複製時直接賦值。

2.對於不可變對象,直接賦值。

3.對於strong特性的對象:如果要求淺複製,直接賦值。如果要求深複製,則要調用copy或mutableCopy方法(當然對於數組或字典來說還是淺複製)。對於copy特性的屬性,使用self.property = theProperty會預設調用copy方法進行複製。


下面建立一個Chocolate類,該類繼承自Desserts類。如果要實現Chocolate類對象的複製,同樣要實現<NSCopying>或<NSMutableCopying>協議中的方法。由於該類繼承自Desserts類,所以Chocolate類的copyWithZone方法必須首先調用父類的copyWithZone方法:

#import "Desserts.h"@interface Chocolate : Desserts <NSCopying>@property (copy, nonatomic) NSMutableString *brand;@property (strong, nonatomic) NSString *details;- (void)setProducer:(NSMutableString *)theProducer              Price:(NSUInteger)thePrice              Brand:(NSMutableString *)theBrand            Details:(NSString *)theDetails;@end
#import "Chocolate.h"@implementation Chocolate- (void)setProducer:(NSMutableString *)theProducer              Price:(NSUInteger)thePrice              Brand:(NSMutableString *)theBrand            Details:(NSString *)theDetails {    [super setProducer:theProducer Price:thePrice];    self.brand   = theBrand;    self.details = theDetails;}- (NSString *)description {    return [NSString stringWithFormat:@"\n\tProducer = %@\n\tPrice = %lu\n\tBrand = %@\n\tDetails = %@", self.producer, self.price, self.brand, self.details];}- (id)copyWithZone:(NSZone *)zone {    [super copyWithZone:zone];        Chocolate *chocolate = [[Chocolate allocWithZone:zone] init];    chocolate.producer   = [self.producer copy];    chocolate.price      = self.price;    chocolate.brand  = self.brand;    chocolate.details  = [self.details copy];    return chocolate;}@end


對於copy特性的屬性,與@synthesize一起使用

@property (copy, nonatomic) NSMutableString *brand;

其合成的setter方法會調用copy方法,其實作類別似於:

- (void)setBrand:(NSMutableString *)theBrand {    if (brand != theBrand) {        brand = [theBrand copy];    }}

由於調用的是copy方法而不是mutableCopy方法,所以建立的是不可變副本,這樣就不用擔心屬性的值被修改,對於copyWithZone方法中的屬性變數直接賦值就可以了。

對於可變類型的屬性(如NSMutableString,NSMutableArray等),copy特性比strong特性更加安全。而對於不可變對象如NSString,NSArray等,如果賦值源是可變對象,那麼也可能會改變NSString的值,如果希望保護該屬性不被修改就用copy特性,否則用strong特性。

例如,對於Desserts的producer屬性,它是strong特性:

@property (strong, nonatomic) NSMutableString *producer;
        Desserts *desserts = [[Desserts alloc] init];        [desserts setProducer:[NSMutableString stringWithString:@"Huizhou"] Price:100];        NSMutableString *mstr = desserts.producer;        NSLog(@"%@", desserts.producer);                [mstr appendString:@" hello factory"];                NSLog(@"%@", desserts.producer);

控制台輸出:

2014-01-31 18:54:07.013 Chocolate[3480:303] Huizhou2014-01-31 18:54:07.015 Chocolate[3480:303] Huizhou hello factory


以上代碼中,將desserts.producer賦值給一個用於臨時任務的mstr,並且對mstr進行修改,那麼desserts.producer將同樣被修改。

如果我們不希望類中的屬性被修改,可以將producer的特性改為copy:

@property (copy, nonatomic) NSMutableString *producer;

隨後用getter方法擷取producer的值並進行修改,將會導致程式崩潰:

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:'

這樣可以達到保護屬性不被修改的目的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.