Polymorphism in Storyboard ViewControllers

孤人 提交于 2019-12-10 11:26:25

问题


I am wondering how can I implement polymorphism in the iPhone XCode storyboard ViewControllers.

This is my problem: Two different ViewControllers in my application are segueing to a common ViewController.

This common ViewController is behaving differently depending on the VC it was segued from - different remote API server calls and CoreData fetches are performed (for the first it presents all users in a table, for another it presents a list of admins - subclass of users, and I may have a third one that will presents filtered list of users).

This common ViewController is very centric in my application, and segues to many other ViewControllers. Therefore, it does not seem right to me to duplicate it on the stroyboard with a subclass.

Passing the list of users to the ViewController is less of an option unfortunately, since different searches on this list are performed and implemented across the ViewController methods.

It makes sense to implement these different behaviours by subclassing and using polymorphism, and assigning the ViewController in the storyboard the subclass according to the origin segue.

Is there any way to set the Storyboard ViewController classes dynamically when segueing?


回答1:


different remote API server calls and CoreData fetches are performed

What you're really calling out here is that the data interface is different than the view interface. That's fine. You should pull out a separate object responsible for fetching data. You can pass that object along to the view controller, rather than polymorphing the view controller. This is called the Strategy pattern, and is very common in Cocoa.

This is almost identical to delegation, which you can also use here. When you segue, the calling view controller sets a delegate on the receiving view controller. That delegate is then responsible for returning the data objects, again freeing the receiving view controller from polymorphing.



来源:https://stackoverflow.com/questions/17924975/polymorphism-in-storyboard-viewcontrollers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!