1、 copy、mutableCopy方法
copy方法傳回對象的不可修改的副本
mutableCopy方法傳回的對象可修改的副本
1)、測試demo
int main(int argc, char * argv[]) {
@autoreleasepool {
NSMutableString *book = [NSMutableString stringWithString:@"chenyu"];
NSMutableString *bookCopy = [book mutableCopy];
[bookCopy replaceCharactersInRange:NSMakeRange(1, 2) withString:@"gong"];
NSLog(@"book is %@", book);
NSLog(@"bookCopy is %@", bookCopy);
NSString *str = @"chenyu";
NSMutableString *strCopy = [str mutableCopy];
[strCopy appendString:@"chenyu"];
NSLog(@"strCopy is:%@", strCopy);
//由于str2是不可變的,是以運作下面會報錯
NSMutableString *str2 = [str copy];
NSLog(@"str copy chen is:%@", str2);
// [str2 appendString:@"chenyu"];
}
}
2)、運作結果
2018-07-15 19:03:35.564049+0800 cyTest[27254:9418105] book is chenyu
2018-07-15 19:03:35.565157+0800 cyTest[27254:9418105] bookCopy is cgongnyu
2018-07-15 19:03:35.566056+0800 cyTest[27254:9418105] strCopy is:chenyuchenyu
2018-07-15 19:03:35.566857+0800 cyTest[27254:9418105] str copy chen is:chenyu
2、NSCopying、NSMutableCopy協定
對象調用copy方法來複制自身的可變副本,需要類 實作NSCopying協定,讓該類實作copyWithZone方法
對象調用mutableCopy方法來複制自身的可變副本,需要類實作NSMutbaleCopying協定,讓類實作mutableCopyWithZone方法demo可以看下下面寫的淺複制
3、深複制和淺複制
我個人了解感覺淺複制是複制後的屬性(指針變量)指向的位址都是同一塊位址,當複制後的對象屬性值發生變化的時候,原始值也發生了變化。
深複制就是複制後的屬性(指針變量)指向的位址不是同一塊位址,當複制後的對象屬性值發生變化的時候,原始值不會發生變化。
1)、淺複制測試Demo
Dog.h
#import <Foundation/Foundation.h>
#ifndef Dog_h
#define Dog_h
@interface Dog : NSObject<NSCopying>
@property (nonatomic, strong) NSMutableString *name;
@property (nonatomic, assign) int age;
@end
#endif /* Dog_h */
Dog.m
#import <Foundation/Foundation.h>
#import "Dog.h"
@implementation Dog
@synthesize name;
@synthesize age;
-(id)copyWithZone:(NSZone *)zone
{
Dog *dog = [[[self class] allocWithZone:zone] init];
dog.name = self.name;
dog.age = self.age;
return dog;
}
@end
main.m
Dog *dog1 = [Dog new];
dog1.name = [NSMutableString stringWithString:@"chen"];
dog1.age = 1;
NSLog(@"dog1.name is %@ and age is %d", dog1.name, dog1.age);
//淺複制
Dog *dog2 = [dog1 copy];
// dog2.name = [NSMutableString stringWithString:@"li"];
[dog2.name replaceCharactersInRange:NSMakeRange(1, 2) withString:@"hel"];
dog2.age = 20;
NSLog(@"dog2.name is %@ and age is %d", dog2.name, dog2.age);
NSLog(@"dog1.name is %@ and age is %d", dog1.name, dog1.age);
2018-07-15 19:03:35.567556+0800 cyTest[27254:9418105] dog1.name is chen and age is 1
2018-07-15 19:03:35.567690+0800 cyTest[27254:9418105] dog2.name is cheln and age is 20
2018-07-15 19:03:35.567768+0800 cyTest[27254:9418105] dog1.name is cheln and age is 1