Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

Objective-C call function on another class?

Here are my objective-c classes:

AppDelegate
SomeScript

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

Thanks, Christian Stewart

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

  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!)

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

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];

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...