NSMutableArray addObject,无法识别的选择器 [英] NSMutableArray addObject, unrecognized selector

查看:60
本文介绍了NSMutableArray addObject,无法识别的选择器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create an array (States) of arrays (Cities). Whenever I try to add an item to my City array I get this error:

'NSInvalidArgumentException',原因:'*** +[NSMutableArrayaddObject:]: 无法识别的选择器发送到类 0x303097a0

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

我的代码如下.它出错的那一行是

My code is as follows. The line it errors on is

 [currentCities addObject:city];

我确定我遇到了一些内存管理问题,因为我仍然不太了解它.希望有人可以向我解释我的错误.

I'm sure I've got some Memory Management problem as I still don't understand it all that well. Was hoping someone could explain my mistake to me.

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

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

which should hopefully fix your problem. Instead of initializing your array, you're sending an init message to a class object, which doesn't do anything. Afterwards, you're currentCities pointer is still not initialized.

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

Even better would be to remove that line and change the 4th line such that you allocate and initialize all in one step:

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

这篇关于NSMutableArray addObject,无法识别的选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆