views:

63

answers:

2

We have 2 files 'MainViewController' and 'View01'
The first file addSubView the second one.

In the first file we have a function named displayView.

I want to be able to call this function from the View01 file is the following code correct

part of View01 file

#import "MainViewController.h"

- (IBAction) changeView:id(sender){
      MainViewControlle *appDelegate = [[UIApplication sharedApplication] delegate];
      [appDelegate displayView:2];
}

is this the correct way to do it?

at the moment I use the NSNotificationCenter to send activate the functions :)

+1  A: 

Hello !

You should try using delegate methods :-)

It works like that :

// Delegate
@protocol MyViewDelegate <NSObject>
- (void)myViewAskedForSomethingWithOrWithoutParameters;

@end

In your view you must have this parameter :

id<MyViewDelegate>  delegate;

And then in your Controller you must implement the delegate

@interface MainViewController : UIViewController <MyViewDelegate> {
}

In your implementation you need to add a :

myView.delegate = self;

And finally in your view when you need to call the function, just do :

[ delegate myViewAskedForSomethingWithOrWithoutParameters ];

Good Luck !

Vinzius
I see. any good tutorial on protocol?? :) thanks both of you for your answers
auslander
Just google it : http://www.google.com/search?q=iphone+protocol+delegate :-) first answers should be good ! like http://www.google.com/search?q=iphone+protocol+delegate
Vinzius
+1  A: 

If I'm not mistaken, your code shouldn't work. Did you try it your self?

[[UIApplication sharedApplication].delegate]

will return your AppDelegate, called something like MyAppDelegate and not MainViewController. However, depending on the template you used or created, your AppDelegate might contain a MainViewController-property, most likely called viewController so you could use

 [appDelegate.viewController displayView:2];

This is the quick way to do it. For a more tidy way, see Vinzius' answer.

Phlibbo