關(guān)于Copy
指針復(fù)制
- (void)viewDidLoad {
[super viewDidLoad];
/*
指針復(fù)制,p1和p2的地址相同
*/
RAPPerson *p1 = [RAPPerson new];
RAPPerson *p2 = p1;
NSLog(@"p1: %p---p2: %p", p1, p2);
}
對象復(fù)制
The exact meaning of “copy” can vary from class to class, but a copy must be a functionally independent object with values identical to the original at the time the copy was made.
- 待復(fù)制的類必須遵守
NSCopying協(xié)議,具體的復(fù)制細節(jié)取決于其對于copyWithZone:方法的實現(xiàn)。 - 根據(jù)文檔描述,復(fù)制出的對象,其值和原始對象相同,但功能上
完全獨立的對象。 - 對于某些類,例如
NSString,NSArray,copy并不總是意味著創(chuàng)建新的對象。系統(tǒng)會出于優(yōu)化內(nèi)存的目的,結(jié)合實際情況判斷是否應(yīng)該創(chuàng)建新的對象,或返回原本的對象。(具體出自哪個資料我忘記了,待查)
- (void)viewDidLoad {
[super viewDidLoad];
/*
對象復(fù)制,p1和p2地址不同
*/
RAPPerson *p1 = [RAPPerson new];
p1.age = 100;
RAPPerson *p2 = [p1 copy];
NSLog(@"%d", p2.age);
NSLog(@"p1: %p---p2: %p", p1, p2);
}
// 下面是RAPPerson類對于NSCopying協(xié)議的實現(xiàn),及其定義的屬性
@interface RAPPerson : NSObject <NSCopying>
/** 年齡 */
@property (nonatomic, assign) int age;
/** 朋友 */
@property (nonatomic, strong) NSArray *friends;
@end
@implementation RAPPerson
- (id)copyWithZone:(NSZone *)zone {
RAPPerson *copy = [[RAPPerson allocWithZone:zone] init];
copy.age = _age;
copy.friends = _friends
return copy;
}
@end
深層復(fù)制
- 根據(jù)
Effective Objective-C 2.0書中Item 22的描述,對象復(fù)制其實是淺層復(fù)制,即只復(fù)制了對象,但對象所攜帶的數(shù)據(jù),即屬性,沒有得到復(fù)制。 - 深層復(fù)制意味著
不僅復(fù)制對象,而且復(fù)制對象的屬性所指向的對象。 - 不管是
NSCopying還是NSMutableCopying協(xié)議,都屬于淺復(fù)制;想要實現(xiàn)深層復(fù)制,必須手動重寫copyWithZone:方法。
@implementation RAPPerson
- (id)copyWithZone:(NSZone *)zone {
RAPPerson *copy = [[RAPPerson allocWithZone:zone] init];
copy.age = _age;
// 不僅復(fù)制對象,還復(fù)制friends這個數(shù)組中所包含的所有對象
copy.friends = [[NSArray alloc] initWithArray:_friends copyItems:YES];
return copy;
}
@end