what's property copy means in Cocoa's Framework?(like UITabBar's items property)

那年仲夏 提交于 2019-12-20 04:28:17

问题


In UITabBar.h, a propery signed copy

@property(nonatomic,copy) NSArray *items; // get/set visible

It's a array And what "copy" means? copy NSArray container obj? copy every obj NSArray contains? or something.

so there's a test

UITabBar* testBar = [[UITabBar alloc] init];
UITabBarItem* item = [[UITabBarItem alloc] init];
NSArray* array = [[NSArray alloc] initWithObjects:item, nil];

NSLog(@"bar:%p,%d", testBar, testBar.retainCount);
NSLog(@"item:%p,%d", item, item.retainCount);
NSLog(@"array:%p,%d", array, array.retainCount);

testBar.items = array;

NSLog(@"that item:%p,%d", [testBar.items lastObject], [[testBar.items lastObject] retainCount]);
NSLog(@"testBar.items:%p,%d", testBar.items, testBar.items.retainCount);

result

bar:0x96a9750,1

item:0x96aa230,2

array:0x96aa280,1

that item:0x96aa230,2

testBar.items:0x96aa280,6

why neither container array nor obj in array has been "copied"?


回答1:


The reason the copy has not been made in this case is that NSArray is immutable. You do not need to make a copy of it to guard against changes to the array, because such changes cannot be made; it is sufficient to retain the same immutable array.

If you try this experiment with NSMutableArray, you will get a different result.




回答2:


Two things:

  • collection -copy is always shallow. It doesn't copy the collections elements (In fact, nothing guarantees that these elements are even copyable – i.e. are conforming to NSCopying protocol). This explains why obj is not copied – it doesn't get any extra retain.

  • Foundation tries to optimizes its implementation of -copy to -retain whenever is possible. For example, -[NSString copy] is a retain for immutable strings. Since collection copies are shallow, the same optimization works for immutable collections. That's why array is not copied but just retained.



来源:https://stackoverflow.com/questions/12031793/whats-property-copy-means-in-cocoas-frameworklike-uitabbars-items-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!