数组的深拷贝与浅拷贝:
- initWithArray:copyItems:
Initializes a newly allocated array using anArray as the source of data objects for the array
- (instancetype)initWithArray:(NSArray *)array copyItems:(BOOL)flag
If flag == YES, each object in array receives a copyWithZone: message to create a copy of the object—objects must conform to the NSCopying protocol. In a managed memory environment, this is instead of the retain message the object would otherwise receive. The object copy is then added to the returned array.
If flag == NO, then in a managed memory environment each object in array simply receives a retain message when it is added to the returned array.
求证:
Model :
#import
@interface Model : NSObject
@property (nonatomic,strong) NSString *name;
@property (nonatomic,assign) NSInteger age;
@end
#import "Model.h"
@implementation Model
- (id)copyWithZone:(NSZone *)zone
{
Model *copyModel = [[[self class] allocWithZone:zone] init];
copyModel.name = self.name;
copyModel.age = self.age;
return copyModel;
}
@end
Model *model1 = [[Model alloc] init];
model1.name = @"model1";
model1.age = 1;
Model *model2 = [[Model alloc] init];
model2.name = @"model2";
model2.age = 2;
Model *model3 = [[Model alloc] init];
model3.name = @"model3";
model3.age = 3;
NSArray *array1 = [NSArray arrayWithObjects:model1,model2,model3, nil];
for (Model *model in array1) {
NSLog(@"model%ld == %p",(long)[array1 indexOfObject:model],model);
}
NSLog(@"array1 == %p",array1);
/*
- (instancetype)initWithArray:(NSArray *)array
copyItems:(BOOL)flag
注意当数组的元素不遵守copy协议的时候flag = NO
只有当数组的元素遵守copy协议的时候 flag = YES,实现深拷贝
*/
NSArray *copyArray1 = [[NSArray alloc] initWithArray:array1 copyItems:NO];
for (Model *model in copyArray1) {
NSLog(@"model%ld == %p",(long)[copyArray1 indexOfObject:model],model);
}
NSLog(@"copyArray1 == %@",copyArray1);
答应结果:
原始的数组array1
2015-09-10 15:17:59.259 CopyTest[30759:2883797] model0 == 0x7f800ac12d90
2015-09-10 15:17:59.259 CopyTest[30759:2883797] model1 == 0x7f800ac0d870
2015-09-10 15:17:59.259 CopyTest[30759:2883797] model2 == 0x7f800ac0ade0
Model遵守 copy协议下 NSArray *copyArray1 = [[NSArray alloc] initWithArray:array1 copyItems:YES];
2015-09-10 15:17:59.260 CopyTest[30759:2883797] model0 == 0x7f800b00abe0
2015-09-10 15:17:59.260 CopyTest[30759:2883797] model1 == 0x7f800b008d90
2015-09-10 15:17:59.260 CopyTest[30759:2883797] model2 == 0x7f800b012650
此文可以参考