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

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

问题描述

寻找这个问题的答案,但我还没有找到合适的答案。我希望你们(和gals)可以帮助我! (这是一个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.

这是我想要做的:

我想创建一个新类,在它自己的文件,有所有的通用方法。然后,当另一个类需要调用方法时,我只需从其他文件调用它。这样,当我想更改方法时,我只需要在一个地方更改它,而不是所有的地方...

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

@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:使用继承

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

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

@end

自然你总是需要 #import commonClass.h

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

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