OC为什么需要copy

来源:互联网 发布:linux操作系统入门书籍 编辑:程序博客网 时间:2024/05/19 19:56

作为一个菜鸟写了几个app后突然发现自己对此产生疑问。
因为很少用到copy,仅仅也就知道深复制、浅复制的一些概念而已,那什么时候使用呢?

+ (NSArray *)retrieveInventoryItems {    NSMutableArray *inventory = [NSMutableArray array];    NSError *err;    NSArray *jsonInventory = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:kInventoryAddress]] options:NSJSONReadingAllowFragments error:&err];    [jsonInventory enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {        NSDictionary *item = obj;        [inventory addObject:[[IODItem alloc] initWithName:[item objectForKey:@"Name"] andPrice:[[item objectForKey:@"Price"] floatValue] andPicFile:[item objectForKey:@"Image"]]];    }];    return [inventory copy];}

看到这里返回了一个copy,原本inventory是mutable版本的,我们用copy就可以返回一个immutable版本的,和强制转换差不多。


还是自己基础不扎实,正如上面所述,不管这里返回一个用copy还是mutableCopy,都是NS类打头类种自带的,如果自己创建了类,想用这个,就必须用到<NSCopying>,重写copyWithZone,来实现对copy的使用。
0 0