Search code examples
iphonefunctiondelegatesparent

Call parent function in xcode iphone development


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


Solution

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