PDA

View Full Version : How do I call a function from another file?




ethana
Aug 5, 2008, 10:42 PM
In MainView.m I have one function -(void)goTell;

I want to be able to call the function from SecondView.m. How do I do this?

I have declared the function in the MainView.h and added #include MainView.h to SecondView.m, but it still doesn't work.

Ethan



ayasin
Aug 5, 2008, 10:47 PM
Your description is insufficent to diagnose the issue. Can you post the code? Also I suggest using #import rather than #include as it will protect against multiple inclusion.

admanimal
Aug 5, 2008, 11:46 PM
In MainView.m I have one function -(void)goTell;

I want to be able to call the function from SecondView.m. How do I do this?

I have declared the function in the MainView.h and added #include MainView.h to SecondView.m, but it still doesn't work.

Ethan

I assume MainView.m contains the implementation of a class called MainView, and likewise SecondView.m has the implementation of a class called SecondView. In order to call a function that is part of the MainView class, you either need an instance of the class to call it on (technically you need an instance to send a message to) or if it is a static function, you can send the method directly to the class name. In your case the function is declared with a - so you're going to need an instance to send the message to.

If you don't understand what I am saying here, you should brush up on Objective-C and object oriented programming.

ethana
Aug 6, 2008, 12:56 AM
Would this suffice?


MainView *myMainView;

[myMainView goTell];


Would that not call the function for the first file?

admanimal
Aug 6, 2008, 01:30 AM
Would this suffice?


MainView *myMainView;

[myMainView goTell];


Would that not call the function for the first file?

Not exactly. First of all, myMainView is nothing, because you haven't allocated any memory for it or initialized it. There is probably another issue depending on what exactly goTell does. Are you actually trying to tell something to the real MainView that you presumably display before going to secondview? Then you need to send the message to the same instance that is actually displayed by your program, not a new instance that you create just to send the message to.

Again, if this doesn't make sense, I would strongly recommend reading up on Objective-C. What you are asking about is one of the very fundamental issues in object-oriented programming that you should really have a good grasp of before you attempt anything as complex as writing an iPhone app.

louden
Aug 6, 2008, 03:27 AM
Your description is insufficent to diagnose the issue. Can you post the code? Also I suggest using #import rather than #include as it will protect against multiple inclusion.

I love reading some of the questions up here.