【发布时间】:2011-09-08 03:04:44
【问题描述】:
我有一个简单的方法可以将数组的第一个元素放在末尾,并将所有内容向下移动一个索引:
-(NSArray*)backUpNotes:(NSArray*)notes {
NSMutableArray* newNotes = [NSMutableArray arrayWithArray:notes];
Note* note = [newNotes objectAtIndex:0];
[newNotes removeObjectAtIndex:0];
[newNotes addObject:note];
return (NSArray*)newNotes;
}
数组 notes 包含两个 Note* 对象,Note A 和 Note B。 行后
Note* note = [newNotes objectAtIndex:0];
note 包含注释 A - 正如预期的那样。 行后
[newNotes removeObjectAtIndex:0];
newNotes 仅包含注释 A --- 这不是预期的。注意 A 在索引 0 处,我可以从调试器中看到。如果我改为这样做
[newNotes removeObjectAtIndex:1];
newNotes 仍然只包含注释 A——这是意料之中的,因为在这种情况下我将删除注释 B。在我看来,我这辈子都无法从这个数组中删除 Note A。我什至尝试过:
[newNotes removeObject:note];
并且仍然有只包含注释 A 的 newNotes - 绝对出乎意料。
任何见解都会令人惊叹。
【问题讨论】:
-
添加注释的 addObject 行是否有原因?
-
毫无疑问,
removeObjectAtIndex:的工作方式与文档中的说明完全一致。恐怕是你把注释 B 和注释 A 混淆了。 -
是的,就是把第一个对象放在数组的末尾。方法是将所有内容向下移动。
-
汤姆 - 我向你保证,我不是。还有其他什么(可能是我的 Note 类的创建方式)或其他一些与内存相关的奇怪问题可能导致这种情况吗?
-
试试这个:
NSLog(@"Before: %p/%p", [newNotes objectAtIndex:0], [newNotes objectAtIndex:1]); [newNotes removeObjectAtIndex:0]; NSLog(@"After: %p", [newNotes objectAtIndex:0]);如果对象没有被移除,那么之前和之后将是一样的。
标签: objective-c ios nsmutablearray