iphone - NSMutableArray addObject,无法识别的选择器

标签 iphone objective-c nsmutablearray

我正在尝试创建数组(城市)的数组(州)。每当我尝试向我的 City 数组添加一个项目时,我都会收到此错误:

'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];
        }
    }

最佳答案

线条:

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

应阅读:

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

这应该有望解决您的问题。您不是初始化数组,而是向类对象发送初始化消息,该类对象不执行任何操作。之后,您的 currentCities 指针仍未初始化。

更好的方法是删除该行并更改第 4 行,这样您就可以一步分配和初始化所有内容:

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

关于iphone - NSMutableArray addObject,无法识别的选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1676789/

相关文章:

iphone - 设置 UITableView 委托(delegate)和数据源

iphone - "Object 0x84be00 of class NSCFString autoreleased with no pool in place - just leaking"- 但在应用程序的第一行!

ios - 如何为自定义 B2B 应用程序添加 Apple ID?

objective-c - NSTableView 的绑定(bind)值,但工具提示也被设置

objective-c - 操作两个数组

iphone - 重新安装 Cydia 应用程序以安装在未越狱的 iPhone 上

objective-c - NSURLConnection 在约 5 分钟后忽略服务器响应——没有超时

objective-c - 来自字符串的 UIControlEvents 变量

用于操作 NSMutableArray 的 IOS MVC 模式和数据 Controller

ios - 如何从服务器将数据存储在 NSmutable 数组中