从其他类 Objective-C 访问方法 [英] Accessing Method from other Classes Objective-C

查看:30
本文介绍了从其他类 Objective-C 访问方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

寻找这个问题的答案,但我还没有找到合适的答案.我希望你们(和女孩)可以帮助我!(这是针对 iPhone 应用的)

Looked for an answer for this question, but I haven't found a suitable one yet. I'm hoping you guys (and gals) can help me out! (This is for an iPhone app)

好的,我有一个 Mutliview 应用程序.每个视图都有自己的类,一切都很愉快.但是,不同的类有时会调用相同的方法.到目前为止,我已经简单地在两个类文件中编写了两次该方法.

Alright, I have a Mutliview application. Each view has it's own class, and everything is happy. However, the different classes sometimes call the same method. Up until now, I have simply wrote that Method twice, in both of the class files.

这就是我想要做的:

我想在它自己的文件中创建一个新类,其中包含所有通用"方法.然后,每当另一个类需要调用该方法时,我只需从另一个文件中调用它.这样,当我想改变Method时,我只需要改变一个地方,而不是所有的地方...

I want to make a new class, in It's own file, that has all the "Common" Methods. Then, whenever another class needs to call the Method, I simply call it from the other file. This way, when I want to change the Method, I only need to change it in one place, and not all the places...

我不确定我会怎么做,这就是我寻求帮助的原因.我对Objective-C有点生疏和陌生,所以漂亮的例子会对我有很大帮助.让我给你一个.

I'm not sure how I'd do this, which is why I'm asking for help. I'm a little rusty and new for Objective-C, so pretty examples will help me a lot. Allow me to give you one.

文件:ViewController1.m

File: ViewController1.m

@implementation ViewController1

//Do Some awesome stuff....

CALL "CommonMethod" HERE

@end

文件:ViewController2.m

File: ViewController2.m

@implementation ViewController2

//Do Some awesome stuff....

CALL "CommonMethod" HERE

@end

文件:CommonClass

File: CommonClass

@implementation commonClass

- (void)CommonMethod:(id)sender
{

//So some awesome generic stuff...



    }
@end

我觉得我需要#import 另一个文件,从类中创建一个对象并从对象中调用方法......我该怎么做?

I feel like I need to #import the other file, make an Object from the class and call the Method from the Object... How do I do that?

再次感谢!

推荐答案

选项 1:

@implementation commonClass
+ (void)CommonMethod:(id)sender  /* note the + sign */
{
//So some awesome generic stuff...
    }
@end

@implementation ViewController2

- (void)do_something... {
    [commonClass CommonMethod];
}


@end

选项 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

选项 3:使用继承(参见此线程中 Totland 先生的描述)

Option 3: use inheritance (see Mr. Totland's description in this thread)

@implementation commonClass
- (void)CommonMethod:(id)sender
{
//So some awesome generic stuff...
    }
@end

/* in your .h file */
@interface ViewController2: commonClass

@end

自然你总是需要在你的视图控制器中#import commonClass.h..

naturally you always need to #import commonClass.h in your view controllers..

这篇关于从其他类 Objective-C 访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆