문제

배열 (도시) 배열 (상태)을 만들려고합니다. 도시 어레이에 항목을 추가하려고 할 때 마다이 오류가 발생합니다.

'nsinvalidargumentexception', 이유 : '*** +[nsmutableArray addObject :] : 인식되지 않은 선택기가 클래스로 전송됩니다 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];
        }
    }
도움이 되었습니까?

해결책

선:

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

읽어야합니다:

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

희망적으로 문제를 해결해야합니다. 배열을 초기화하는 대신, 클래스 객체에 이르 메시지를 보내는 것은 아무것도하지 않습니다. 그 후, 당신은 현재 도시 포인터가 아직 초기화되지 않았습니다.

더 나은 라인을 제거하고 4 번째 줄을 변경하여 한 단계로 모두 할당하고 초기화하는 것입니다.

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

다른 팁

NSMutableARRAY에서 일종의 초기 라이저를 호출해야합니까? initwithcapacity 또는 그와 비슷한 것이 있습니까? 당신이 그것을 떠나면 무엇을 얻는 지 잘 모르겠습니다.

** 방금 테스트했습니다. [[nsmutablearray alloc] init]로 만들면 괜찮을 것입니다.

저에게는 초기화 문제였습니다.

변경해야했습니다

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

에게

NSMutableArray *myArray  = [NSMutableArray new]; // initialized!
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top