问题
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
-copyis always shallow. It doesn't copy the collections elements (In fact, nothing guarantees that these elements are even copyable – i.e. are conforming toNSCopyingprotocol). This explains whyobjis not copied – it doesn't get any extra retain.Foundation tries to optimizes its implementation of
-copyto-retainwhenever 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 whyarrayis not copied but just retained.
来源:https://stackoverflow.com/questions/12031793/whats-property-copy-means-in-cocoas-frameworklike-uitabbars-items-property