将数据传递给下一个ViewController时出错

时间:2014-03-29 15:15:50

标签: ios objective-c uiviewcontroller nsstring uistoryboard

我正在尝试在ViewControllers之间传递数据。数据字符串是从UIPickerView获得的。但是,我收到了一个错误。首先,我在这里填充UIPickerView

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

            if([courseArray count]==0)
            {
                courseArray = [NSMutableArray arrayWithObject:val];
            }
            else
            {
                [courseArray addObject:val];
            }
        }
        [_coursePicker reloadAllComponents];
        _coursePicker.hidden=false;
    }

    [_txtBox resignFirstResponder];
}

以下是我尝试将数据传递给第二个ViewControllerGradesViewController)的方式:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    GradesViewController *controller = segue.destinationViewController;
    @try
    {
        [controller setCourseToSearch:[NSString stringWithString:selectedCourse]];
    }
    @catch (NSException *exception)
    {
        NSLog(@"%@ --- %@",exception, selectedCourse);
        if([selectedCourse isKindOfClass:[NSString class]])
        {
            NSLog(@"it IS a string");
        }
        else
        {
            NSLog(@"it is NOT a string");
        }
    }
}

最后,我在这里设置selectedCourse

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    selectedCourse = [NSString stringWithString:[courseArray objectAtIndex:[pickerView selectedRowInComponent:0]]];
}

GradesViewController中的属性定义如下:

@property (assign) NSString *courseToSearch;

prepareForSegue中的异常处理输出以下内容:

2014-03-29 11:00:08.292 WebServiceTest[46154:60b] -[UIViewController setCourseToSearch:]: unrecognized selector sent to instance 0xe29ac60 --- 43-214: Course Name
2014-03-29 11:00:08.292 WebServiceTest[46154:60b] it IS a string

为什么我在发送NSString时发送了“无法识别的选择器”?作业selectedCourse = [NSString stringWithString:[courseArray objectAtIndex:[pickerView selectedRowInComponent:0]]];不应该确保它是NSString吗?

1 个答案:

答案 0 :(得分:1)

问题不在于字符串,而在于您的故事板,因为您还没有设置正确的视图控制器类。这就是你在-[UIViewController setCourseToSearch:]: unrecognised ...

中获得 UIViewController 的原因

更正故事板中的班级名称。

然后,更改字符串管理,这样您就不会重复创建新字符串(即删除stringWithString:用法)并更改此属性:

@property (assign) NSString *courseToSearch;

@property (strong) NSString *courseToSearch;

因为您应该保留(或复制)对象。