如何从另一个类中调用方法(iOS) [英] How to call method from one class in another (iOS)

查看:267
本文介绍了如何从另一个类中调用方法(iOS)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个非常基本的问题,但我已经搜遍了所有的搜索,并且无法找到足以让我理解的答案。

This a very basic question but I've searched all over and been unable to find an answer that explains well enough for me to get my head around it.

我想要做的是在我的iOS应用程序的一个类中创建一个方法,然后从我的应用程序中的其他类调用该方法。有人可以准确解释我需要做些什么来实现这一目标吗?任何帮助都会非常感激,因为到目前为止我的所有尝试都失败了!

What I want to do is create a method in one class of my iOS app and then call that method from other classes in my app. Could someone explain exactly what I need to do to achieve this? Any help would be greatly appreciated as all my attempts so far have failed!

谢谢。

推荐答案

Objective-C:

您必须导入包含您要使用的方法的类的标头( ClassYouWantToUse.h )进入要在( TargetClass )使用它的类。

You have to import the header of the class that contains the method you want to use (ClassYouWantToUse.h) into the class you want to use it at (TargetClass).

在TargetClass中.h或TargetClass.m(取决于你想要的范围):

Inside the TargetClass.h or TargetClass.m (depending on the scope you want to give it):

#import "ClassYouWantToUse.h"

然后在目标类中创建要在类中使用的类的实例,如下所示:

Then create an instance of the class you want to use inside the target class either as a property like this:

@property (nonatomic,strong) ClassYouWantToUse *classObject;

或者像这样的实例变量:

Or as an instance variable like this:

ClassYouWantToUse *classObject;

确保初始化它! (通常在ViewDidLoad中):

Make sure you initialize it! (usually inside ViewDidLoad):

classObject = [[ClassYouWantToUse alloc] init];

现在您可以调用该类中的任何公共方法,如下所示:

Now you can call any public methods from that class like this:

[classObject theClassMethodWithParam:param1 andSecondParam:param2];

注意: ClassYouWantToUse类必须具有您要制作的方法通过在头文件中声明它们来访问其他人:

Note: The ClassYouWantToUse class must have the methods that you want to make accessible to others by declaring them in the header file:

- (void)theClassMethodWithParam:(UIImage*)someImage andSecondParam:(NSString*)someText;

否则您将无法看到这些方法。

Otherwise you won't be able to see these methods.

Swift:

在swift中真的没什么特别的,只需添加此作为参考。

Theres really nothing special about it in swift, just adding this as a reference.

在swift中,您只需创建要使用的类的实例:

In swift you simply create an instance of the class you want to use:

let classObject = ClassYouWantToUse()

并直接使用它:

classObject.theClassMethodWithParam(param1, andSecondParam:param2)

这篇关于如何从另一个类中调用方法(iOS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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