2009-11-04 3 views
5

배열 (도시) 배열을 만들려고합니다. City 배열에 항목을 추가하려고하면이 오류가 발생합니다.NSMutableArray addObject, 인식 할 수없는 selector

'NSInvalidArgumentException', reason: '*** +[NSMutableArray addObject:]: unrecognized selector sent to class 0x303097a0

내 코드는 다음과 같습니다. 나는 아직 잘 모든 것을 이해하지 않는 한 나는 약간의 메모리 관리 문제를 가지고 확신

[currentCities addObject:city]; 

입니다에 선은 오류를 그. 누군가 내 실수를 설명 할 수 있기를 바랬다.

if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL) == SQLITE_OK){ 
     // We need to keep track of the state we are on 
     NSString *state = @"none"; 
     NSMutableArray *currentCities = [NSMutableArray alloc]; 

     // We "step" through the results - once for each row 
     while (sqlite3_step(statement) == SQLITE_ROW){ 
      // The second parameter indicates the column index into the result set. 
      int primaryKey = sqlite3_column_int(statement, 0); 
      City *city = [[City alloc] initWithPrimaryKey:primaryKey database:db]; 

      if (![state isEqualToString:city.state]) 
      { 
       // We switched states 
       state = [[NSString alloc] initWithString:city.state]; 

       // Add the old array to the states array 
       [self.states addObject:currentCities]; 

       // set up a new cities array 
       currentCities = [NSMutableArray init]; 
      } 

      [currentCities addObject:city]; 
      [city release]; 
     } 
    } 

답변

9

의 선 :

// set up a new cities array 
currentCities = [NSMutableArray init]; 

읽어야합니다 희망이 당신의 문제를 해결해야

// set up a new cities array 
[currentCities init]; 

. 배열을 초기화하는 대신 클래스 객체에 초기화 메시지를 보냅니다. 아무것도하지 않습니다. 그 후에, 당신은 현재 도시 포인터가 아직 초기화되지 않았습니다.

더 나은은 한 번에 모든 것을 줄을 제거하고 할당하도록 4 라인을 변경하고 초기화하는 것입니다 :

NSMutableArray *currentCities = [[NSMutableArray alloc] init]; 
+0

NSMutableArray *myArray = [NSMutableArray mutableCopy]; // not initialized. don't know why this even compiles [myArray addObject:someObject]; // crashed 

에서 변경했다 (이 당신은 안하지만 할 경우), 그것은'읽기 currentCities의 = 필요 [currentCities는 초기화하기 ]'. NSArray 이니셜 라이저는 수신기를 반환하지 않으며 클래스 초기화 자도이를 보장하지 않습니다. – Chuck

+0

나는 [currentCities init]이있는 이유; 왜냐하면 우리는 다음 상태로 전환 할 때 새로운 인스턴스를 초기화해야하기 때문입니다. 해당 행을 변경하면이 문제가 해결되었지만 다른 문제가 발생했지만 언급 한 두 번째 단계 ([[NSMutableArray alloc] init))를 추가하면 해당 문제가 해결되었습니다. 감사합니다. –

+0

새 인스턴스를 초기화하는 경우 새 인스턴스도 할당해야합니다. – Wevah

3

NSMutableArray에서 일종의 초기화 프로그램을 호출해야합니다. 그렇습니까? initWithCapacity 또는 이와 비슷한 것? 당신이 그것을 내버려두면 당신이 얻는 것을 확신 할 수 없습니다.

** 방금 테스트했습니다. 그것을 [[NSMutableArray alloc] init]으로 만들어라. 그러면 괜찮을 것이다.

1

그것은 나를 위해 초기화 문제였다.

는 별도의 초기화를 할 경우

NSMutableArray *myArray = [NSMutableArray new]; // initialized! 
관련 문제