簡體   English   中英

將數據傳遞到下一個ViewController時出錯

[英]Error when passing data to the next ViewController

我試圖在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嗎?

問題不在於字符串,而是故事板,因為您沒有設置正確的視圖控制器類。 這就是為什么在-[UIViewController setCourseToSearch:]: unrecognised ...獲得UIViewController的原因-[UIViewController setCourseToSearch:]: unrecognised ...

在情節提要中更正課程名稱。

然后,更改您的字符串管理,以免您反復創建新字符串(即刪除stringWithString:用法)並更改此屬性:

@property (assign) NSString *courseToSearch;

@property (strong) NSString *courseToSearch;

因為您應該保留(或復制)對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM