[英]One controller to rule them all
I have helper class which contain different methods. 我有包含不同方法的帮助程序类。 I dо not want to include it's header file at every class that I have in my app. 我不想在应用程序中的每个类中都包含它的头文件。 That approach is against DNRY I think. 我认为这种做法违反了DNRY。 Here is why I decide to create one "master" class called AppController and each class in my app to inherit it. 这就是为什么我决定创建一个名为AppController的“主”类,并在我的应用中创建每个类来继承它的原因。
Here is what I do 这是我的工作
AppController.h AppController.h
#import <Foundation/Foundation.h>
#import "Helper.h"
@interface AppController : NSObject
{
ivars...
}
some methods ...
@end;
myClass.h myClass.h
import "AppController.h"
@interface myClass : AppController
{
ivars...
}
some methods
@end
So far, so good. 到现在为止还挺好。 The problem rise when some class needs to inherit not NSObject, but let's say UIViewController. 当某些类需要继承而不是NSObject时,问题就出现了,比如说UIViewController。 This is the moment where my AppController become useless. 这是我的AppController变得无用的那一刻。 I know that Objective-c is not support multiple inheritance. 我知道Objective-c不支持多重继承。 I have read somewhere that can be done using composition, but I can't figure out how to do that. 我读过一些可以使用合成的方法,但是我不知道该怎么做。 I will be grateful if someone gives me some examples. 如果有人给我一些例子,我将不胜感激。
I have read somewhere that can be done using composition, but I can't figure out how to do that. 我读过一些可以使用合成的方法,但是我不知道该怎么做。 I will be grateful if someone gives me some examples. 如果有人给我一些例子,我将不胜感激。
Yes, composition is how you do this. 是的,构图就是您的操作方式。 Your inheritance approach is wrong on several levels. 您的继承方法在几个级别上都是错误的。
Here is how you approach this: 这是您的处理方式:
The vast majority of things people would normally use a "utility" dumping ground for are better solved with categories and functions in ObjC. 人们通常会使用“实用程序”垃圾场进行处理的绝大多数事情都可以通过ObjC中的类别和功能得到更好的解决。 The remainder are usually best served using delegation (but that's another topic). 其余的通常最好使用委托服务(但这是另一个主题)。
A better way would be to add the #import "Helper.h"
to your project's precompiled header file (YourAppName-Prefix.pch). 更好的方法是将#import "Helper.h"
添加到项目的预编译头文件(YourAppName-Prefix.pch)中。 Doing that is equivalent to importing your helper class header file in every other file of your project, and you're managing it from one spot only. 这样做等同于将助手类头文件导入项目的每个其他文件中,而您仅从一个位置进行管理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.