【问题标题】:Dynamically selecting different viewControllers动态选择不同的 viewController
【发布时间】:2010-10-31 17:02:01
【问题描述】:

我有一个问题,我认为可能是直截了当的,但我似乎无法解决它。

我有一个从 NSDictionaries 数组加载的 tableview。 Each Dictionary has a title (shown in the row) and an associated nssstring representing a viewcontroller that should be pushed onto the stack when the row is selected.也就是说,选择“A”行需要初始化“aViewController”实例并入栈,选择“B”行需要初始化“bViewController”实例并入栈,以此类推。

我最初只是将所有可能的值硬编码到 didSelectRow 中。但我真的很希望能够动态地动态生成 viewController。我发现了一些类似问题的 C++ 示例,这些示例使我找到了下面的代码。但我似乎无法做到正确,并且不确定我是否在正确的轨道上寻找目标 c 解决方案。有人有什么想法吗?

这是不工作的 didSelectRow 代码:

Class cls = [selectedRow valueForKey:@"viewController"]; 
if (cls!= nil)
{
id myNewController = [[cls alloc] init];    
}


[[self navigationController] pushViewController:myNewController animated:YES];
[myController release];

【问题讨论】:

    标签: iphone objective-c uiviewcontroller dynamic-typing


    【解决方案1】:

    您是在字典中存储实际的类还是类名(作为 NSString)?

    如果您在字典中存储的值是 NSString,我认为您不能只分配 Class cls = someNSString;

    但是,您可以这样做:

    NSString *controllerClassName = [selectedRow valueForKey:@"viewController"];
    if (controllerClassName != nil) {
         id myNewController = [[NSClassFromString(controllerClassName) alloc] init];
         [[self navigationController] pushViewController:myNewController animated:YES];
         [myNewController release];
    }
    

    只需将 Class 存储在字典中,而不是 NSString 表示:

    【讨论】:

    • "NSClassFromString"。如此明显,如此直观,但当你一无所知时,很难找到。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多