开发者

Call parent function in xcode iphone development

We have 2 files 'MainViewController' and 'View01'

The first file addSubView the second one.

In the first f开发者_C百科ile 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 :)


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 !


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜