2012-03-02 131 views
2

我想删除索引1处的对象,但代码无法编译。从NSMutableArray中删除对象

我也不明白这一点:我设置“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 [email protected]"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; 
} 

回答

9

这应该是

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

这种方法显然是NSMutableArray文档中所述。在提出问题前,请务必查阅正确的文档。

+0

谢谢。这有助于我! – Ben 2012-03-02 04:01:55

2

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

您应该改用

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

如果你想知道为什么它0工作,我猜是因为0 == NULL == nil这是一个指向一个空的对象,因此它解释为无对象,而不是一个索引(它不会像你所期望的那样)。

+0

谢谢。这有助于我! – Ben 2012-03-02 04:02:54

2

您正在使用removeObject而不是removeObjectAtIndex。

+0

谢谢。这有助于我! – Ben 2012-03-02 04:02:37