简体   繁体   中英

Can't call controller method from delegate

I'm trying to do something like this: http://www.pushplay.net/2009/05/framework-for-having-multiple-views-in-an-iphone-app/

So far I've got this structure: appDelegate -> rootViewController -> welcomeViewController

I've a method (doSomething) in my delegate, which is called by an IBAction in welcomeViewController. It works, I can do an NSlog in doSomething and it shows the method is being called within the delegate.

The problem is when I run a command like [rootViewController loadNewView] in my doSomething method (in the delegate), it does nothing. It doesn't error, it just does nothing.

I've been reading and seen protocols and notifications are suggested, but I'd like to know why this method using the delegate doesn't work and if there is any way to fix it.

SurveyClientAppDelegate.h

@interface SurveyClientAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    RootViewController *rootViewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet RootViewController *rootViewController;

-(void)doSomething;

@end

SurveyClientAppDelegate.m

- (void)doSomething {
    NSLog(@"Attempt: rootViewController loadLocationList");
    [rootViewController loadLocationList];
}

RootViewController.h

@interface RootViewController : UIViewController {
    WelcomeViewController *welcomeView;
}

@property (nonatomic, retain) WelcomeViewController *welcomeView;
@property (nonatomic, retain) SurveyListViewController *surveyList;

-(void)loadLocationList;

RootViewController.m

- (void)loadLocationList
{
    NSLog(@"RootViewController: loadLocationList");
}

WelcomeViewController.h

@interface WelcomeViewController : UIViewController

-(IBAction)viewList:(id)sender;
-(void)loadLocationList;

WelcomeViewController.m

- (void)viewList:(id)sender
{
    SurveyClientAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    [appDelegate doSomething];
}

Are you keeping a reference to rootViewContoller in your welcomeViewController? It's possible (and likely) that rootViewController will be released before you can call methods on it.

This is a good time to use delegates . You mention calling a method "in the delegate" but without seeing any of your code it's difficult to tell if you're using it correctly or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM