我正在尝试创建数组(Cities)的数组(States)。每当我尝试将一个项目添加到我的City数组时,我都会收到此错误:
'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];
}
}
答案 0 :(得分:9)
行:
// set up a new cities array
currentCities = [NSMutableArray init];
应阅读:
// set up a new cities array
[currentCities init];
应该有希望解决您的问题。您不是初始化数组,而是向类对象发送init消息,该对象不执行任何操作。之后,你的currentCities指针仍未初始化。
更好的方法是删除该行并更改第4行,以便一步分配和初始化所有内容:
NSMutableArray *currentCities = [[NSMutableArray alloc] init];
答案 1 :(得分:3)
你需要在NSMutableArray上调用某种初始化器,不是吗? initWithCapacity,还是那样的?不知道如果你把它拿走,你会得到什么。
**刚试过它。设为[[NSMutableArray alloc] init],你会没事的。
答案 2 :(得分:1)
这对我来说是初始化问题。
不得不改变
NSMutableArray *myArray = [NSMutableArray mutableCopy]; // not initialized. don't know why this even compiles
[myArray addObject:someObject]; // crashed
到
NSMutableArray *myArray = [NSMutableArray new]; // initialized!