【问题标题】:Can I use the same method passing in different UIViewController subclasses?我可以使用传递不同 UIViewController 子类的相同方法吗?
【发布时间】:2011-03-07 22:48:36
【问题描述】:

我有一个自定义类,它可以与 Web 服务对话。目前,我有一个 UIViewController 子类使用我的服务类并且可以正常获取数据。

我将 UIViewController 子类的引用作为方法参数发送到服务查询方法 (queryServiceWithParent)。

然后我将 UIViewController 子类存储在一个属性中,以便稍后在类中使用它。

NeighbourhoodData.h:

NeighbourhoodDetailTableViewController *viewController;

NeighbourhoodData.m:

- (void)queryServiceWithParent:(UIViewController *)controller {

    viewController = (NeighbourhoodDetailTableViewController *)controller;

}

我的问题是我现在想在另一个视图中使用这个类和不同的 UIViewController 子类。

我可以通过相同的方法传递子类,因为我的参数只是一个 UIViewController,但我需要将我的类属性设置为正确的 UIViewController 子类类型。

有什么办法可以做到这一点吗?我对整个 iPhone 开发场景非常陌生,所以我想到的唯一方法是创建一个新类,但我认为必须有更好的方法......

【问题讨论】:

    标签: iphone objective-c ios uiviewcontroller


    【解决方案1】:

    您可以询问id 这是什么类型的课程。这样的事情可能会起作用:

    - (void)doStuffWithMyViewController:(UIViewController *)controller
    {
        if ([controller isKindOfClass:[FirstViewControllerSubclass class]])
        {
            //The controller is a FirstViewControllerSubclass or a subclass of FirstViewControllerSubclass
        }
    
        if ([controller isKindOfClass:[SecondViewControllerSubclass class]])
        {
            //The controller is a SecondViewControllerSubclass or a subclass of SecondViewControllerSubclass
        }
    }
    

    从那里你可以根据它们是哪个子类或你想要的任何东西来做不同的事情。

    另一件要考虑的事情是为两个视图控制器创建一个公共超类,如果它们之间存在共享功能

    【讨论】:

    • 感谢您的回复。我的问题不是发送哪个 UIViewController 子类,而是将“viewController”属性设置为发送该方法的子类类型,因为稍后我需要在类中使用“viewController”属性。尽管您对超类的建议听起来可能会奏效...
    • 超类方法奏效了,非常感谢您的帮助!
    【解决方案2】:

    您要么创建一个类方法供其他类访问,要么您必须学习设置委托以使您当前的类成为其他类的委托。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2016-05-05
      • 2018-06-05
      相关资源
      最近更新 更多