Eth*_*ick 19 iphone methods class object objective-c
寻找这个问题的答案,但我还没有找到合适的答案.我希望你们(和女孩们)可以帮助我!(这适用于iPhone应用程序)
好吧,我有一个Mutliview应用程序.每个视图都有自己的类,一切都很开心.但是,不同的类有时会调用相同的方法.到目前为止,我只是在两个类文件中编写了两次Method.
这是我想要做的事情:
我想在它自己的文件中创建一个具有所有"常用"方法的新类.然后,每当另一个类需要调用Method时,我只需从另一个文件中调用它.这样,当我想要改变方法时,我只需要在一个地方改变它,而不是所有地方......
我不确定我是怎么做到的,这就是为什么我要求帮助.对于Objective-C我有点生疏和新的,所以漂亮的例子对我很有帮助.请允许我给你一个.
文件:ViewController1.m
@implementation ViewController1
//Do Some awesome stuff....
CALL "CommonMethod" HERE
@end
Run Code Online (Sandbox Code Playgroud)
文件:ViewController2.m
@implementation ViewController2
//Do Some awesome stuff....
CALL "CommonMethod" HERE
@end
Run Code Online (Sandbox Code Playgroud)
文件:CommonClass
@implementation commonClass
- (void)CommonMethod:(id)sender
{
//So some awesome generic stuff...
}
@end
Run Code Online (Sandbox Code Playgroud)
我觉得我需要#import另一个文件,从类中创建一个Object并从Object调用Method ...我该怎么做?
再次感谢!
Nir*_*evy 26
选项1:
@implementation commonClass
+ (void)CommonMethod:(id)sender /* note the + sign */
{
//So some awesome generic stuff...
}
@end
@implementation ViewController2
- (void)do_something... {
[commonClass CommonMethod];
}
@end
Run Code Online (Sandbox Code Playgroud)
选项2:
@implementation commonClass
- (void)CommonMethod:(id)sender
{
//So some awesome generic stuff...
}
@end
@implementation ViewController2
- (void)do_something... {
commonClass *c=[[commonClass alloc] init];
[c CommonMethod];
[c release];
}
@end
Run Code Online (Sandbox Code Playgroud)
选项3:使用继承(参见Totland先生在此主题中的描述)
@implementation commonClass
- (void)CommonMethod:(id)sender
{
//So some awesome generic stuff...
}
@end
/* in your .h file */
@interface ViewController2: commonClass
@end
Run Code Online (Sandbox Code Playgroud)
自然你总是需要#import commonClass.h在你的视图控制器..