1

在 UITabBar.h 中,一个属性签名的副本

@property(nonatomic,copy) NSArray *items; // 获取/设置可见

这是一个数组 “复制”是什么意思?复制 NSArray 容器 obj?复制每个 obj NSArray 包含的内容?或者其他的东西。

所以有一个测试

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);

结果

栏:0x96a9750,1

项目:0x96aa230,2

数组:0x96aa280,1

那个项目:0x96aa230,2

testBar.items:0x96aa280,6

为什么容器数组和数组中的 obj 都没有被“复制”?

4

2 回答 2

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.

于 2012-08-20T03:28:31.150 回答
1

在这种情况下没有制作副本的原因NSArray不可变的。您不需要复制它来防止对数组进行更改,因为无法进行此类更改;保留相同的不可变数组就足够了。

如果你尝试这个实验NSMutableArray,你会得到不同的结果。

于 2012-08-20T03:05:41.507 回答