删除没有任何语句的数组

时间:2014-02-20 04:52:20

标签: ios objective-c nsmutablearray

我在名为NSMutableArray的{​​{1}}数组中添加了6个对象。这6个对象的名称为gamesABCDE

F

我想从NSMutableArray *games = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",nil]; 数组中删除3个元素,例如应从数组中删除gamesDEFAB应保留在数组中。

我想要简单的代码,不涉及任何循环语句。

是否可以在不使用循环的情况下从数组中删除元素?

5 个答案:

答案 0 :(得分:3)

使用此代码我在我的机器上测试它工作正常

 NSMutableArray *games = [[NSMutableArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",nil];

    NSRange r;
    r.location = 3;
    r.length = [games count]-3;
    [games removeObjectsInRange:r];
    NSLog(@"array elements are %@",games);

答案 1 :(得分:1)

查看NSMutableArray class reference并尝试:

- (void)removeObjectsInRange:(NSRange)aRange;

- (void)removeObjectsAtIndexes:(NSIndexSet *)indexes;

答案 2 :(得分:0)

NSMutableArray *games = [[NSMUltipleArray alloc] initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",nil];

    int i;
    for(i=0; i<[myArray count]; i++) {
        id element = [myArray objectAtIndex:i];
        if(element == ...) {
            [myArray removeObjectAtIndex:i];
            i--;
        }
    }

element =要删除的元素与之匹配

没有循环

NSMutableArray *games = [[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",nil];

    NSRange remove;
    remove.location = 3;
    remove.length = [games count]-3;
    [games removeObjectsInRange:remove];
    NSLog(@"after removed elements  = %@",games);

答案 3 :(得分:0)

嗨,我不确定你是想丢掉数组的最后三个对象还是保留前三个。无论如何,我们可以在原始数组上调用subarrayWithRange:来获取包含要保留的对象的新数组。或者,如果您不想创建新数组并且原始数组是NSMutable数组,您可以使用removeObjectsInRange:

答案 4 :(得分:0)

您可以使用NSPredicate过滤数组非常简单,没有索引或特定对象的范围只需过滤谓词即可过滤array

NSMutableArray *game=[[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C",@"D",@"E",@"F" ,nil];
    game = [NSMutableArray arrayWithArray: [game filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"NOT (SELF IN %@)",[NSArray arrayWithObjects:@"D", @"E",@"F", nil]]]];