view controller not appearing in iOS 5 project - objective-c

i started a single view template in Xcode 4.2(recently upgraded to Xcode 4.2 and ios5)
so now i have only one view controller.
I added a new class to the project which is a subclass of UIViewcontroller.
Now in the main controller class viewdidLoad method
- (void)viewDidLoad
{
// Override point for customization after application launch.
[super viewDidLoad];
[self presentQuizcontroller];
}
-(void) presentQuizcontroller
{
_QuizController = [[[Quiz alloc] initWithNibName:#"Quiz" bundle:nil] autorelease];
_QuizController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:_QuizController animated:YES]; // Do any additional setup after loading the view, typically from a nib.
}
the problem is in my Quiz class
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
the initWithNibName method does get called(i checked by using breakpoint) but it doesn't passes the condition of if(self) . and hence the view don't appears.
Any ideas?
Edit
After the first answer i tried this way too
- (void)viewDidLoad
{
// Override point for customization after application launch.
[super viewDidLoad];
}
-(void) presentQuizcontroller
{
_QuizController = [[[Quiz alloc] initWithNibName:#"Quiz" bundle:nil] autorelease];
_QuizController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:_QuizController animated:YES]; // Do any additional setup after loading the view, typically from a nib.
}
-(void) awakeFromNib
{
[self presentQuizcontroller];
}
same thing Quiz.m initwithnib name method does not passes the condition if(self).

I think you need to use awakefromnib.
Here is the Link for another StackOverflow post if you want to read more.

PresentModalViewController is depreciated, I think you should now use presentViewController instead of it.
Are you sure that "Quiz" is the name of your file? That string should be same as the name of your xib file, namely something like "QuizController" or "QuizViewController"
Make sure the xib file is properly connected to header/implementation files by checking:
Owner of the xib file should be set as the viewController
View on the xib file (the one above all if you have multiple views) should be connected to viewControllers view.

Related

Custom initialisation while using storyboard

Prior to storyboards, and working with .xib files, I used this piece of code to do screen adjustments during init.
- (id)initForNewItem:(BOOL)isNew {
self = [super initWithNibName:#"NAME" bundle:nil];
if (self) {
if (isNew) {
// Place some buttons only when isNew is true
}
}
return self;
}
Then I also implemented this to generate an exception when initWithNibName is directly called because I wanted to avoid that:
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
#throw [NSException exceptionWithName:#"Wrong initializer" reason:#"Use initForNewItem:" userInfo:nil];
return nil;
}
Then another viewcontroller could call the custom init and the screen would be set:
MyViewController *myViewController = [[MyViewController alloc] initForNewItem:YES]; // Or NO ofcourse depending on the situation.
Now I'm using storyboard and initWithNibName is never called. Instead only initWithCoder is called but this method can only be called by the storyboard right? So how would I do something similar while using storyboard?
You wouldn't do this with storyboards.
The way to do it is to use properties to give the correct values once the view controller has been initialised.
This is done in - (void)prepareForSegue:(UIStoryBoardSegue *)segue sender:(id)sender.
You can access segue.destinationViewController and then use this to put values in to.

setAction: in NSViewController

It might be helpful to know that I come from a iOS background and that this is one of my first OS X projects.
In my project, I have a NSView subclass and a NSViewController and load the view in the controller.
- (void)loadView
{
StartView *view = [StartView alloc] initWithFrame:frame]; // frame exists
self.view = view;
}
The view has a NSButton-property btnNewthat I add in initWithFrame:.
- (id)initWithFrame:(NSRect)frame
{
self = [super initWithFrame:frame];
if (self) {
self.btnNew = [[NSButton alloc] initWithFrame:NSRectFromCGRect(CGRectMake(350, 180, 300, 60))];
[self addSubview:self.btnNew];
}
return self;
}
In loadView: I try to set the action and target.
- (void)loadView
{
StartView *view = [StartView alloc] initWithFrame:frame]; // frame exists
[view.btnNew setTarget:self];
[view.btnNew setAction:#selector(createNew:)];
self.view = view;
}
The createNew: function exists, off course.
However, when clicking the button, the app crashes. When I move the setTarget: and the setAction: into the view and perform them on self.btnNew, it works, but I think that's not how you should work with events and user interaction in a decent MVC-architecture.
The problem is with the self in [view.btnNew setTarget:self];, I guess. If I grab the target with view.btnNew.target, this is a nil object (0x000…000). Self exists & view.btnNew exists.
Am I doing something wrong? Or should I really listen to the click in the view and work with a delegate or a notification (I guess not?)
I found it out myself, with help from Niel Deckx.
The problem was ARC. The ViewController got dealloced before the click happened, which explains the NSObject does not respond to selector: the target doesn't exist anymore.
The easy solution is to have the ViewController as a (strong?) property where you create it.

UIViewController not calling viewDidLoad & not creating UIView causing crash

I've been at this for a few hours now. I've got several View Controllers in this project and not a single one is causing issues but now all of a sudden this new one is. I even deleted it and made a "Test" View Controller, but no dice. The best I can tell it is not actually creating its view, thus when the view is referenced the app crashes. The test VC has no added or deleted code except for a log statement in the -viewDidLoad method. I am not overriding -loadView. I have tried adding the view to a subview, have tried pushing the VC into the Navigation Controller, I have even tried simply logging test.view. I have tried creating the VC with a NIB and have tried it without one. Absolutely nothing works at all. Any help will be appreciated.
Where VC is being created inside of another VC. The log statment causes the crash. But so does adding as a subview and even pushing into nav controller.
TestViewController *test = [[TestViewController alloc] init];
NSLog(#"test view = ", test.view);
Implementation of TestViewController.
#implementation TestViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
NSLog(#"view = %#", self.view);
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
I'd say to double check all the connections from the view. Especially if its been copied or moved as its easy to leave a connection to an old VC
if you are not using ARC in your project then dont check the autolayout box for the nib file. If you are using ARC then the connections of it to the file's owner can be the only issue.
if you use xib,and the items is copied from other xib or storyboard ,make sure the root view is exist,and drag tothe file's owner.

Subclassing a subclass of UIViewController load issue

So, here's the issue. I'm relatively new to iOS programming, and I've taken on a giant project.
I'm working on a game with multiple levels which basically follow the same pattern, but have different sprite images and values, and I just decided to lay out all the levels in IB for speed's sake (not necessarily best practices, I know, but work with me). Each "level" has its own view controller, along the lines of "FireLevel1ViewController," "FireLevel2ViewController," etc. All of these view controllers inherit from a custom subclass of UIViewController I created called "GameController."
My problem is, when I open each level on my test device, GameController's viewDidLoad is getting called before the init or viewDidLoad methods of my subclass controllers, and so none of my level images/values are getting assigned to the superclass properties. Specifically, I have a pause menu that ought to be hidden at the outset of the level (I am doing setHidden in GameController's viewDidLoad), but since GameController's viewDidLoad runs before FireLevel1 has a chance to associate the correct IB property with PauseMenu, GameController just hides an empty view, and the actual PauseMenu never gets hidden.
I may have multiple problems going on here, but mostly I think I'm not really understanding correctly how to subclass a subclass of UIViewController and how to get the second subclass's properties/values/images to work in the first subclass's methods.
Thanks so much for any help! I hope that question made sense...
Code for GameController:
#implementation GameController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self)
{
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self.view addSubview:pauseMenu];
[pauseMenu addSubview:helpMenu];
//Hides the pause and help menus until their respective buttons are pressed
[pauseMenu setHidden:YES];
[helpMenu setHidden:YES];
isPaused = NO;
}
Code for FireLevel1Controller:
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if(self)
{
theMainview = mainview;
theScene = scene;
theBG = bg;
theHudView = hud;
thePauseView = pauseMenu;
theHelpView = helpMenu;
}
return self;
}
-(void)viewDidLoad
{
[super viewDidLoad];
firstTurret = [[StationaryEnemy alloc]init:turretImage1 baseView:base1];
secondTurret = [[StationaryEnemy alloc]init:turretImage2 baseView:base2];
NSLog(#"I'm in view did load");
}
Did you try using viewWillAppear? That method should be called after all the visible UI elements have been initialized.
Ahhhh I figured it out - I was accidentally negating my variables. I should've been doing mainview = theMainview; instead of theMainview = mainview - I was just assigning them all to zero. I also moved them all out of init into viewDidLoad, and moved [super viewDidLoad] underneath them, and now it works perfectly!

Infinite loop when overriding initWithCoder

I have a UIViewController with some controllers and some views. Two of these views (Grid Cell) are other nibs. I've got outlets from the Grid Cells to File's Owner, but they aren't loaded automatically.
So I try to override GridCell.m's initWithCoder.
This starts an infinite loop.
I know it's possible to just override initWithFrame and add the subview from code, but this is not what I want. I want to be able to move the view around in Interface Builder and have Xcode initialize the view with the right frame.
How do I go about achieving this?
EDIT 1
I'm trying to get it working with the help of Alexander. This is how I've now got it set up:
MainView has UIView with a Custom class set as GridCell. It got an outlet in the MainView/File's Owner.
Removed all init-code from GridCell.m and set up an outlet to my custom class
The MainView don't still display the GridCell though. There's no error, just a lonely, empty space where the red switch should be. What am I doing wrong?
I'm very close to just doing this programmatically. I would love to learn how to this with nibs though.
Loading the nib causes initWithCoder to be called again, so you only want to do so if the subclass currently doesn't have any subviews.
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
if (self.subviews.count == 0) {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
UIView *subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
subview.frame = self.bounds;
[self addSubview:subview];
}
}
return self;
}
Loading a nib will cause the corresponding owner in a
-(id) initWithCoder:(NSCoder *) coder;
call
Therefore your coude in this method:
self = [[[NSBundle mainBundle] loadNibNamed: #"GridCell"
owner: self
options: nil] objectAtIndex:0];
will cause again a call of the initWithCoder method. That's because you try to load the nib again. If you define a custom UIView and create a nib file to lay out its subviews you can't just add a UIView to another nib file, change the class name in IB to your custom class and expect the nib loading system to figure it out.
What you could do is the following:
Your custom view's nib file needs to have the 'File's owner' class set to your custom view class and you need to have an outlet in your custom class called 'toplevelSubView' connected to a view in your custom view nib file that is acting as a container for all the subviews. Add additional outlets to your view class and connect up the subviews to 'File's owner' (your custom UIView). (See https://stackoverflow.com/a/7589220/925622)
EDIT
Okay, to answer your edited question I would do the following:
Go to the nib file where you want to include the custom view with it's nib file layouting it.
Do not make it to the custom view (GridCell) itself, instead make a view which will contain your grid cell (gridCellContainer for example, but it should be a UIView)
Customize the initWithFrame method within your custom view like you did in initWithCoder:
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"GridCell" owner:self options:nil];
self = [nib objectAtIndex:0];
self.frame = frame;
}
return self;
}
And then, in the viewController which is the fileOwner for the view where you want to include your custom view (the one with the gridCellContainer view) do this in viewDidLoad e.g.
//...
GridCell *gridCell = [[GridCell alloc] initWithFrame:self.viewGridCellContainer.bounds];
[self.viewGridCellContainer addSubview:gridCell];
Now eveything should work as you expected
The File's owner will not get a call to
-(id) initWithCoder:(NSCoder *) coder;
when loading a xib.
However, every view defined in that xib will get a call to
-(id) initWithCoder:(NSCoder *) coder;
when loading a xib.
If you have a subclass of a UIView (i.e. GridCell) defined in a xib and also try to load that same xib in your subclass's initWithCoder, you will end up with an infinite loop. However, I can't see what will the use case be.
Usually you design your UIView's subclass (i.e. GridCell) in one xib, then use that subclass in a view controller’s xib for example.
Also, can't see a use case where your custom view will have a subview in it's initWithCoder, i.e.
-(id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
if (self) {
if (self.subviews.count == 0) {
UINib *nib = [UINib nibWithNibName:NSStringFromClass([self class]) bundle:nil];
UIView *subview = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
subview.frame = self.bounds;
[self addSubview:subview];
}
}
return self;
}
Unless you want to be able to override its view hierarchy on demand in some other xib. Which IMO assumes an external dependency (i.e. a hierarchy defined in another xib) and kinda defeats the purpose of having a reusable UIView in the first place.
Bare in mind that when loading a xib, passing an instance as the File's owner, will have all of its IBOutlet(s) set. In that case, you would be replacing self (i.e. GridCell) with whatever the root view in that GridCell.xib is, losing all IBOutlet connections in the process.
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"GridCell" owner:self options:nil];
self = [nib objectAtIndex:0];
self.frame = frame;
}
return self;
}
There is a more detailed post on "How to implement a reusable UIView." that goes into a bit more detail as well and hopefully clears things up.
loadNibNamed:: will call initWithCoder:
Why don't you follow this pattern?
-(id)initWithCoder:(NSCoder *)coder
{
if (self = [super initWithcoder:coder]) {
// do stuff here ...
}
return self;
}
Does [super initWithcoder:coder] do things that you want to avoid?
I had the same issue when I'm trying to override initWithsomething method, we need
-(id)initWithsomething:(Something *)something
{
if (self = [super initWithsomething:something]) {
// do stuff here ...
}
return self;
}
instead
-(id)initWithsomething:(Something *)something
{
if (self = [super init]) {
// do stuff here ...
}
return self;
}