将值传递给目标控制器

时间:2012-12-26 14:50:09

标签: iphone objective-c ios

我将ID从UITABLEVIEWCONTROLLER传递给另一个UITABLEVIEWCONTROLLER,但它会抛出以下错误。

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UITabBarController setCityId:]: unrecognized selector sent to instance 0x75225e0'

这里是prepareForSegue函数:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"cityPushToTab"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        featuredViewController *destViewController = segue.destinationViewController;
        destViewController.cityId = [productKeys objectAtIndex:indexPath.row];
    }

}

在我调用特色控制器的cityId之前,该功能运行良好。我试图记录打印正确值的productKeys,但是当我尝试将值赋给目标视图控制器对象时它终止。请帮忙。

1 个答案:

答案 0 :(得分:1)

您确定destViewController属于班级featuredViewController吗?我确定不是。崩溃日志告诉它是UITabBarController

我建议创建一个继承自UITabBarController的类。我称之为MyTabBarViewController。将故事板中标签栏控制器的类设置为这个新类。

MyTabBarViewController.h中,创建一个属性:

@property (nonatomic, strong) id cityId;

(请注意,cityId可以是您需要的任何类型,例如NSStringNSNumber,...)。

然后,更改您的prepareForSegue代码:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"cityPushToTab"]) {
        NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
        MyTabBarViewController *destViewController = segue.destinationViewController;
        destViewController.cityId = [productKeys objectAtIndex:indexPath.row];
    }
}

接下来,在标签栏中的4个视图控制器的.m文件中,您可以使用此代码访问cityId

// Cast the viewcontroller's tab bar to your class
MyTabBarViewController *tabBarController = (MyTabBarViewController*)self.tabBarController;

// Access your property
id cityId = tabBarController.cityId;
// You can test to see if it works by casting to an NSString and NSLog it
NSString *cityIdString = (NSString*) tabBarController.cityId;
NSLog (@"%@", cityIdString);