从NSMutableArray中删除对象

时间:2016-07-15 01:51:07

标签: objective-c nsarray

如何删除NSMutableArray中的对象?我尝试使用[myArray removeObject:@"Music"]但它没有用。我无法使用[myArray removeObjectAtIndex:4]因为数组的位置是动态的。这里的问题是在数组里面我有7个对象,每个对象都是一个NSDictionary。我需要删除具有音乐标题或标记的对象。我该怎么做?谢谢!

2 个答案:

答案 0 :(得分:2)

你删除的字符串是@" Music"。它包含在数组中。 因此,您将获得require字符串的索引。

BOOL Success = [yourArray containsObject:@"Music"];  // that bool response is whether the string present or not
if(Success){
    NSInteger index = [yourArray indexOfObject:@"Music"];   // it return the matched string index value form array
   [yourArray removeObjectAtIndex:index]
}

答案 1 :(得分:0)

首先找到应该删除的元素。

// this is one of many ways to find some things in array, in this case returning an index of the match
NSIndexSet *indexSet = [myArray indexesOfObjectPassingTest:^(id o, NSUInteger idx, BOOL *stop){ 
    NSDictionary *d = (NSDictionary *)o;
    BOOL isMusic = [d[@"title"] isEqualToString:@"Music"];  // put the real test here
    return isMusic;
}];

现在removeObjectAtIndex:将按预期工作。

[indexSet enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop){
    [myArray removeObjectAtIndex:idx];
}];

编辑 - 更简洁,用以下内容替换上面的枚举:

[myArray removeObjectsAtIndexes:indexSet];