Reputation: 5234
With the way I have things set up in my first iPad project, I've been curious why regular method calls aren't working the way I think they would.
In a view, inside initWithFrame I make a delegate pointer like this:
mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];
And make a button like this:
CGRect backBTNFrame = CGRectMake(25, 30, 140, 52);
backButton_video = [[UIButton alloc] init];
backButton_video.frame = backBTNFrame;
backBtnImg_video = [UIImage imageNamed:@"SHIP_button_back.png"];
[backButton_video setImage:backBtnImg_video forState:UIControlStateNormal];
backButton_video.backgroundColor = [UIColor clearColor];
[self addSubview:backButton_video];
[backButton_video addTarget:self
action:@selector(kill_timers)
forControlEvents:UIControlEventTouchUpInside];
[backButton_video addTarget:del.switchVC
action:@selector(gotoMain)
forControlEvents:UIControlEventTouchUpInside];
I click the button and it calls a method from a view controller:
- (void)gotoMain{
NSLog(@"switch to main");
for(UIView *v in [containerView subviews]) {
[v removeFromSuperview];
}
MainMenu *mainMenu = [[MainMenu alloc] init];
mainMenu.frame = CGRectMake(0, -20, 1024, 768);
[containerView insertSubview:mainMenu atIndex:0];
[mainMenu release];
}
This gets rid of the view I was in, and adds the main menu view. This works fine.
However, if I make a delegate pointer like how it was before and call the self method kill_timers and the view controller method gotoMain, it will not work:
mainMenuAppDelegate *del = (mainMenuAppDelegate *)[[UIApplication sharedApplication] delegate];
[self kill_timers];
[del.switchVC gotoMain];
In the console I see the message that it kills the timer, which it does, but I have a NSLog ready to fire in the view controller, but nothing shows up. Just ain't happenin. Any clues? Why would the button and regular method call behave differently?
Upvotes: 0
Views: 287
Reputation: 9126
That self in the
[self kill_timers];
literally means that the object (self) is told to do something. What you really want to do is tell your delegate to do something. This is not good design practice.
If you want your delegate to do something, then use NSNotificationCenter.
In your AppDelegate's applicationDidFinishLaunching:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(kill_timers)
name:@"Kill Timers" object:nil];
Then, when you want to call this created observer:
[[NSNotificationCenter defaultCenter] postNotificationName:@"Kill Timers" object:nil];
This will fire the method, without the messy design flaws associated with having multiple instances of your AppDelegate.
Upvotes: 1