copy的概念特點
-
copy產(chǎn)生一個新副本的過程,利用一個原對象產(chǎn)生一個新對象
- copy:創(chuàng)建一個不可變的副本(NSString;NSArray;NSDictionary;)
- mutableCopy :創(chuàng)建一個可變的副本 (NSMutableDictionary; NSMutableArray;NSMutableString)
修改新文件,不會影響原文件
修改原文件御蒲,不會影響新文件
淺拷貝:如果沒有生成新對象我們稱為淺拷貝仇穗,本質(zhì)是指針拷貝制恍,指向的還是同一處
深拷貝:如果生成了新的對象举农,我們稱為深拷貝,本質(zhì)就是創(chuàng)建了一個新的對象
NSString * str = @"demo";
NSMutableString *copyStr = [str copy];
NSMutableString *mcopyStr = [str mutableCopy];
NSLog(@"str = %@ copyStr = %@ mcopyStr = %@",str,copyStr,mcopyStr);
NSLog(@"str = %p copyStr = %p mcopyStr = %p",str,copyStr,mcopyStr);
log:
str = demo copyStr = demo mcopyStr = demo
str = 0x10aa760c8 copyStr = 0x10aa760c8 mcopyStr = 0x60000025aca0
結(jié)論:
1、copy和mutableCopy拷貝出來的對象中的內(nèi)容和以前內(nèi)容一致
2突颊、不可變的字符串通過copy操作,沒有生成新的對象潘悼,而是指向同一內(nèi)存
3律秃、不可變的字符串通過mutableCopy操作,生成新的可變對象治唤,所以需要生成一個新對象
NSMutableString *str1 = [NSMutableString stringWithFormat:@"demo"];
NSMutableString *copyStr1 = [str1 mutableCopy];
NSMutableString *mcopyStr1 = [str1 mutableCopy];
NSLog(@"str = %@ copyStr = %@ mcopyStr = %@",str1,copyStr1,mcopyStr1);
NSLog(@"str = %p copyStr = %p mcopyStr = %p",str1,copyStr1,mcopyStr1);
log:
str = demo copyStr = demo mcopyStr = demo
str = 0x6040002570a0 copyStr = 0x604000257310 mcopyStr = 0x6040002570d0
結(jié)論:
1棒动、copy和mutableCopy拷貝出來的對象中的內(nèi)容和以前內(nèi)容一致
2、可變的字符串通過copy操作宾添,生成新的對象
3船惨、可變的字符串通過mutableCopy操作,生成新的可變對象
自定義類的實現(xiàn)copy(NSCopying協(xié)議)
- 若想令自己寫的類具有copy功能辞槐,則需要實現(xiàn)NSCopying掷漱、NSMutableCopying協(xié)議
- (id)copyWithZone:(nullable NSZone *)zone;
- (id)mutableCopyWithZone:(nullable NSZone *)zone;
看個例子
#import <Foundation/Foundation.h>
@interface Phone : NSObject<NSCopying>
@property (nonatomic,copy,readonly) NSString *name;
@property (nonatomic,assign,readonly) NSInteger price;
- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price;
@end
#import "Phone.h"
@implementation Phone
- (instancetype)initWithName:(NSString *)name withPrice:(NSInteger)price{
self = [super init];
if (self) {
_name = [name copy];
_price = price;
}
return self;
}
- (id)copyWithZone:(NSZone *)zone{
Phone *phone = [[[self class] allocWithZone:zone] initWithName:_name withPrice:_price];
return phone;
}
Phone *p = [[Phone alloc]initWithName:@"iPhone" withPrice:999];
NSLog(@"%p--%@--%zd",p,p.name,p.price);
Phone *p1 = [p copy];
NSLog(@"%p--%@--%zd",p1,p1.name,p1.price);
log:
0x60000002cce0--iPhone--999
0x6000000371c0--iPhone--999
注:在- (id)copyWithZone:(NSZone *)zone方法中,一定要通過[self class]方法返回的對象調(diào)用allocWithZone:方法榄檬。因為指針可能實際指向的是PersonModel的子類卜范。這種情況下,通過調(diào)用[self class]鹿榜,就可以返回正確的類的類型對象海雪。