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

标签 objective-c ios nsmutablearray

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

-(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/

相关文章:

objective-c - 获取字体的最大高度

ios - 从另一个 View 重新加载 TableView

iphone - ViewController 的 NSMutableArray

ios - 可拖动 View 之间的 UIBezierPath

objective-c - 避免 "NSArray was mutated while being enumerated"

ios - 创建 NSDictionary 的 NSMutalbeArray 时出现 EXC_BAD_ACCESS

objective-c - 从JSON加载属性,获取“消息发送到已释放实例”

ios - UIAlertController 内存泄漏

ios - 如何将自定义值插入现有的 Plist 数组数据?

c# - 清除 WebView 缓存 xamarin IOS