2012-03-02 4 views
2

인덱스 1에서 객체를 제거하려고하지만 코드가 컴파일되지 않습니다.NSMutableArray에서 객체 제거

나는 또한 이것을 이해하지 못한다 : 나는 색인 0에서 "iphone"문자열을 설정했다. 그런 다음 색인 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

2

removeObject:(id)obj은 인덱스와 함께하지만 실제 개체에는 사용할 수 없습니다.

당신은 사용해야하는 대신이 0 작동 이유를 궁금해하는 경우, 내가 생각

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

null 객체에 대한 포인터, 그래서이 전무 개체로 해석이야 0 == NULL == nil 때문에 그 대신 인덱스 (그 네가 기대하는 것처럼 행동하지 않을 것이다).

+0

감사합니다. 이게 나를 도와 줘! – Ben

2

removeObjectAtIndex 대신 removeObject를 사용하고 있습니다.

+0

감사합니다. 이게 나를 도와 줘! – Ben

관련 문제