Objective-C 调用另一个类的函数? [英] Objective-C call function on another class?

查看:34
本文介绍了Objective-C 调用另一个类的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的 Objective-C 类:

Here are my objective-c classes:

AppDelegate
SomeScript

如何从应用程序委托或任何其他类调用 SomeScript 类上的登录函数?

How might I call the function loggedIn on the SomeScript class from the app-delegate or any other class?

谢谢,克里斯蒂安·斯图尔特

Thanks, Christian Stewart

推荐答案

(我假设 loggedIn 是一个不带参数的实例方法.)首先,几个术语问题:

(I'll assume loggedIn is an instance method taking no parameters.) First, several terminology issues:

  1. 它们不是函数,而是方法(不过思路相同).
  2. 您不调用方法,而是发送消息(不过,通常是相同的想法).
  3. 最重要的是,我们通常不向类发送消息,而是向这些类的实例发送消息.(如果您无法想象其中的区别,请想象一下将一封信放入邮箱的想法与将一封信放入您的邮箱.只有一个才有意义!)莉>
  1. They're not functions, they're methods (same idea, though).
  2. You don't call methods, you send messages (usually same idea, though).
  3. Most importantly, we usually send messages not to classes, but to instances of those classes. (If you can't visualize the difference, imagine placing a letter in the idea of mailboxes vs. placing a letter in your mailbox. Only one makes sense!)

因此,我们的新计划是首先实例化 SomeScript,然后向实例发送消息.

So, our new plan is to first instantiate SomeScript, then send a message to the instance.

SomeScript* myScript = [[SomeScript alloc] init]; //First, we create an instance of SomeScript
[myScript loggedIn]; //Next, we send the loggedIn message to our new instance

这很好.然而!我敢打赌,您希望您的脚本保留下来以备后用.因此,我们真的应该让它成为您的应用程序委托的实例变量.因此,相反,在 AppDelegate.h 中,将其添加到大括号内:

This is good. However! I bet you want your script to stick around for later use. Thus, we should really make it an instance variable of your app delegate. So, instead, in AppDelegate.h, add this inside the braces:

SomeScript* myScript;

现在我们的变量将保留下来,我们之前的第一行变得简单:

Now our variable will stick around, and our first line from before becomes simply:

myScript = [[SomeScript alloc] init];

最后一个问题:我们不想每次调用 loggedIn 时都创建一个新脚本(我假设)!因此,您应该将实例化放置在只会运行一次的地方(例如,application:DidFinishLaunchingWithOptions:).达达!

Last complication: we don't want to create a new script every time we call loggedIn (I assume)! So, you should place the instantiation somewhere it will only be run once (for example, application:DidFinishLaunchingWithOptions:). Ta-da!

这篇关于Objective-C 调用另一个类的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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