从NSMutableArray中删除对象

时间:2012-03-02 01:28:17

标签: objective-c nsmutablearray

我正在尝试删除索引1处的对象,但代码将无法编译。

我也不明白这一点:我将“iphone”字符串设置为索引0,然后将其从索引0中删除,但输出仍然首先显示“iphone”。任何人都可以向我解释一下吗?

int main (int argc, const char * argv[])
{    
    @autoreleasepool {

        //create three string objetc
        NSString *banana  = @"This is banana";
        NSString *apple = @"This is apple";
        NSString *iphone =@"This is iPhone";

        //create  an empty array
        NSMutableArray *itemList = [NSMutableArray array];

        // add the item to the array
        [itemList addObject:banana];
        [itemList addObject:apple];

        // put the iphone to the at first

        [itemList insertObject:iphone atIndex:0];

        for (NSString *l in itemList) {
            NSLog(@"The  Item in the list is %@",l);
        }
        [itemList removeObject:0];
        [itemList removeObject:1];// this is not allow  it

        NSLog(@"now the first item in the list is %@",[itemList objectAtIndex:0]);
        NSLog(@"now the second time in the list is %@",[itemList objectAtIndex:1]);
        NSLog(@"now the thrid item in the list is %@",[itemList objectAtIndex:2]);

    }
    return 0;
}

4 个答案:

答案 0 :(得分:9)

那应该是

[itemList removeObjectAtIndex:0];
[itemList removeObjectAtIndex:1];

NSMutableArray的文档中明确说明了此方法。在提出问题之前,请务必查阅正确的文档。

答案 1 :(得分:2)

方法removeObject:(id)obj不适用于索引,但适用于实际对象。

你应该使用

[list removeObjectAtIndex:0];
[list removeObjectAtIndex:1];

如果你想知道为什么它适用于0,我想因为0 == NULL == nil是一个指向空对象的指针,所以它被解释为nil对象而不是索引(它不会表现就像你期望的那样。)

答案 2 :(得分:2)

您正在使用removeObject而不是removeObjectAtIndex。

答案 3 :(得分:2)

使用:

[itemList removeObjectAtIndex:0];

Here's a detailed guide NSMutableArray

相关问题