Reputation:
I'm slowly picking up Objective-C and the iPhoneSDK but I'm having some problems getting my head around the MVC pattern.
I'm fleshing out a game which I hope will have screens like a splash screen, title, help etc. What I'm currently doing is creating a new UIViewController and a new nib for each of these screens, is this the right practice? In the main AppDelegate I've created methods that show the views and add them with [window addSubView:controller.view]. What I'm finding is that with the show/hide code sat in the AppDelegate, I have to create a reference of the AppDelegate in the loaded controller in order to target the hide code. This seems a bit awkward but I expect I'm probably approaching this wrong, how do you guys usually do this sort of thing?
// example from AppDelegate
-(IBAction)showHelp:(id)sender
{
helpScreen = [[helpController alloc] initWithNibName:@"helpView" bundle:nil];
// send copy of self in order to target closeHelp method from InterfaceBuilder
helpScreen.appDel = self;
helpScreen.view.alpha = 0;
[window addSubview:helpScreen.view];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:1.0];
helpScreen.view.alpha = 1.0;
[UIView commitAnimations];
}
Many Thanks,
Upvotes: 2
Views: 3488
Reputation: 58804
UIViewController and a new nib for each of these screens, is this the right practice
Yeap!
[window addSubView:controller.view]
Are you also removing the old views at the end of the animation? You should be, otherwise you would have multiple view controllers running at once, something that you really don't want.
What I'm finding is that with the show/hide code sat in the AppDelegate, I have to create a reference of the AppDelegate in the loaded controller in order to target the hide code
Well somewhere you need the code that's responsible for switching views, and if the views can control this switching then they do need a way to trigger that. Rather than app delegate I usually have a RootViewController that performs these changes.
I tend to derive each of these views from a base class that has a delegate property for performing these changes. When the views need to change they call functions in the delegate. These are usually;
E.g.
// your root controller
-(void) changeView:(UIViewController) newController
{
newController = blah blah;
newController.delegate = self;
// add newController view, remove old one etc
}
// new controller
-(void) userPressedHelp
{
UIViewController* help = blah blah;
[self.delegate pushView: newController];
}
// help controller
-(void) userPressedOk
{
[self.delegate popView];
}
Upvotes: 2
Reputation: 13775
That seems reasonable to me. I'm pretty new to Obj-C but that's how I've done an application.
As long as the ViewControllers don't have knowledge of each other, I think you are doing just fine.
Upvotes: 0