Objective-C 中如何不重复代码? (又名多重继承)
当您有 UIViewController
和 UITableViewController
类,并且您想让这两个类在它们的 - (void)viewDidLoad
中执行一些常见的操作时,您怎么能在 Objective-C 中实现这个目标而不需要实际复制你的代码?
我尝试创建继承 UIViewController
的 MyUIViewController
并在其中实现 viewDidLoad
。显然,这与 UIViewController
类完美配合,但在 UITableViewController
中不起作用,因为我不能简单地将 @interface MyTableViewController : UITableViewController
替换为@interface MyTableViewController:MyUIViewController
。
我相信这个主题是关于 Objective-C 语言中的“多重继承”,但除了弄清楚 Objective-C 中的不同之处之外,我真的很想知道人们如何做这样的事情?
When you have an UIViewController
and UITableViewController
classes and you wanted to let these two do some common stuff in their - (void)viewDidLoad
how could you achieve this in Objective-C without actually duplicating your code?
I tried to create MyUIViewController
inheriting UIViewController
and implement viewDidLoad
in there. This perfectly works with UIViewController
classes obviously, but won't work in UITableViewController
, since I can't simply replace @interface MyTableViewController : UITableViewController
with @interface MyTableViewController : MyUIViewController
.
I believe this topic is about "multiple inheritance" in Objective-C language, but other than figuring out what's different in Objective-C, I'd really like to know how to do guys do such thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此帖子提供了一些很好的信息。主要选项之一是创建一个具有共享功能的类,并将其作为实例变量保存,然后在
forwardInitation
中将消息转发给它。This thread has some good information. One of your main options is to make a class with that shared functionality and hold it as an instance variable, then forward messages to it in
forwardInvocation
.