添加到NSMutableArray时出错

时间:2014-03-29 04:11:17

标签: ios objective-c nsmutablearray nsarray

以下代码位于我的实现文件中:

NSMutableArray *courseArray;


- (IBAction)btnClick:(id)sender
{
    NSDictionary *courseNames;
    if(![_txtBox.text isEqual:@""]) //if not empty
    {
        courseNames = [self retrieveCourseNamesForSemester:_txtBox.text];
        for (NSString *key in courseNames)
        {
            NSString *val = [NSString stringWithFormat:@"%@-%@",key,[courseNames objectForKey:key]];
            _txtView.text = val;
            @try
            {
                [courseArray addObject:val];
            }
            @catch(NSException *e)
            {
                NSLog(@"Exception: %@ for value = %@", e, val);
            }
        }
    }
    [_coursePicker reloadAllComponents];
    _coursePicker.hidden=false;
    [_txtBox resignFirstResponder];
}

如果您看到对NSLog()的调用,则会收到以下错误消息:

2014-03-29 00:02:25.830 WebServiceTest[44646:60b] Exception: -[__NSArrayI addObject:]: unrecognized selector sent to instance 0x8d82c30 for value = 73-522-Course Name

编辑:此外,courseArray填充了viewDidLoad中的示例数据:

- (void)viewDidLoad
{
    [super viewDidLoad];
    courseArray = @[@"Australia (AUD)", @"China (CNY)",
                    @"France (EUR)", @"Great Britain (GBP)", @"Japan (JPY)"];
}

我应该在哪个地方定义courseArray会占用NSString个对象吗?

2 个答案:

答案 0 :(得分:2)

viewDidLoad中的代码创建一个不可变数组。你需要制作一个可变副本,比如这个

(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    courseArray = [@[@"(AUD)", @"(CNY)", @"(EUR)"] mutableCopy];
}

答案 1 :(得分:0)

试试这段代码,

for (NSString *key in courseNames)
{
    NSString *val = [NSString stringWithFormat:@"%@-%@",key,[courseNames objectForKey:key]];
            _txtView.text = val;


    if ([CourseArray count]==0)
    {
        CourseArray= [NSMutableArray arrayWithObject:val];
    }
    else
    {
        [CourseArray addObject:val];
    }
}