gpt4 book ai didi

objective-c - NSMutableArray removeObjectAtIndex :0 not behaving as expected

转载 作者:行者123 更新时间:2023-11-28 17:43:04 25 4
gpt4 key购买 nike

我有一个简单的方法,可以将数组的第一个元素放在末尾,然后将所有元素向下移动一个索引:

-(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 包含 Note A -- 正如预期的那样。行后

[newNotes removeObjectAtIndex:0];

newNotes 仅包含注释 A --- 这不是预期的。注意 A 在索引 0 处,我可以从调试器中看到它。如果我改为这样做

[newNotes removeObjectAtIndex:1];

newNotes 仍然只包含注释 A -- 这是预期的,因为在这种情况下我要删除注释 B。在我看来,我这辈子都不能从这个数组中删除音符 A。我什至尝试这样做:

[newNotes removeObject:note];

并且仍然有仅包含注释 A 的新注释——绝对出乎意料。

任何见解都会令人惊叹。

最佳答案

试试这个:

NSMutableArray* newNotes = [NSMutableArray arrayWithArray:notes];
for (Note *n in newNotes) {
if ([n isEqual:note]) {
[newNotes removeObject:n];
break;
}
}

或者:

int x = 0;
NSMutableArray* newNotes = [NSMutableArray arrayWithArray:notes];
for (Note *n in newNotes) {
if ([n isEqual:note]) {
break;
}
++x;
}
[newNotes removeObjectAtIndex:x];

关于objective-c - NSMutableArray removeObjectAtIndex :0 not behaving as expected,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7342697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com