【发布时间】:2014-02-20 04:58:34
【问题描述】:
以下两个示例似乎都可以正常工作。在示例 1 中,widget 在 while 循环之前创建:
-(int)compareWidgets { // Example 1
int count = 0;
NSMutableArray *widgetsCopy = [self.widgets mutableCopy];
Widgets *widget = [[Widgets alloc]init]; // HERE ? or...
while (widgetsCopy.count) {
widget = [widgetsCopy lastObject];
[widgetsCopy removeLastObject];
for (Widgets *compareWidget in widgetsCopy)
if (compareWidget.value == widget.value)
count += 1;
}
return count;
}
在示例 2 中,widget 在 while 循环中创建...
-(int)compareWidgets { // Example 2
int count = 0;
NSMutableArray *widgetsCopy = [self.widgets mutableCopy];
while (widgetsCopy.count) {
Widgets *widget = [widgetsCopy lastObject]; // HERE ?
[widgetsCopy removeLastObject];
for (Widgets *compareWidget in widgetsCopy)
if (compareWidget.value == widget.value)
count += 1;
}
return count;
}
Q1:在示例 1 中,widget 仅被分配/初始化一次,然后似乎为数组的每次迭代重新分配。在示例 2 中,从未使用过 alloc/init,但 widget 再次通过每次迭代成功分配。为什么这是可能的?哪个例子是正确的或可取的?
Q2:另外,在任何一种情况下,widget 都会被分配给一个数组对象,该数组对象会立即从其数组中删除:[widgetsCopy removeLastObject]。既然 widget 指向的对象已经从它的数组中删除了,为什么此时 widget 不是 nil —— 为什么它继续保持正确的值呢? p>
谢谢。
【问题讨论】:
-
你应该阅读the iOS memory-management basics。现代 iOS 使用一个称为 ARC 的系统,它消除了很多样板,但您仍然需要熟悉基础知识,从您的问题来看,您还没有。
标签: objective-c arrays pointers allocation