2012-03-02 186 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

相關問題