When do I need to call -[UIViewController initWithNibName:bundle:]? - ios

In post Using initWithNibName changes absolutely nothing, he shows two uses of the same View Nib definition, in the first case, he simply calls alloc/init and the second, he specifies initWithNibName.
So, while this always works:
MyViewController *vctrlr = [[MyViewController alloc] initWithNibName:#"MyViewController" bundle:nil];
[self.navigationController pushViewController:vctrlr animated:YES];
[vctrlr release];
The following works for all the View Controllers I've inherited, but not mine!
TheirViewController *vctrlr = [[TheirViewController alloc] init];
[self.navigationController pushViewController:vctrlr animated:YES];
[vctrlr release];
New to iOS programming, I inherited some code. All the View Controllers' views are defined in IB, but there was inconsistent allocation/init creation of those view controllers. I created a new View Controller and XIB, but it does not work unless I use initWithNibName (it crashes when I push the view controller onto the Nav Controller). I cannot tell how my view controller is different than the others... any hints? I was able to delete the initNibName usage for all the other view controllers in the app except mine.

You can pass any string name to initWithNibName:. You are not just restricted to calling initWithNibName:#"MyClassName" when your class is called MyClassName. It could be initWithNibName:#"MyClassNameAlternateLayout".
This becomes useful if you need to load a different nib depending on what the app needs to do. While I try to have one nib per view controller per device category (iPhone or iPad) whenever possible to make development and maintenance simpler, I could understand if a developer would want to provide a different layout or different functionality at times.
Another important point is that initWithNibName:bundle: is the designated initializer for UIViewController. When you call -[[UIViewController alloc] init], then initWithNibName:bundle: is called behind the scenes. You can verify this with a symbolic breakpoint. In other words, if you simply want the default behavior, it is expected that you can call -[[UIViewController alloc] init] and the designated initializer will be called implicitly.
If, however, you are calling -[[UIViewController alloc] init] and not getting the expected behavior, it's likely that your UIViewController subclass has implemented - (id)init incorrectly. The implementation should look like one of these two examples:
- (id)init
{
self = [super init];
if (self) {
// custom initialization
}
return self;
}
or
- (id)init
{
NSString *aNibName = #"WhateverYouWant";
NSBundle *aBundle = [NSBundle mainBundle]; // or whatever bundle you want
self = [self initWithNibName:aNibName bundle:aBundle];
if (self) {
// custom initialization
}
return self;
}

If you want to work following code:
MyViewController *vctrlr = [[MyViewController alloc] inil];
[self.navigationController pushViewController:vctrlr animated:YES];
Then you should implement following both methods in MyViewController:
- (id)init
{
self = [super initWithNibName:#"MyViewController" bundle:nil];
if (self != nil)
{
// Do initialization if needed
}
return self;
}
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)bundle
{
NSAssert(NO, #"Init with nib");
return nil;
}

Related

About using init methods

I made a test app to understand how exactly init methods work. In my simple UIViewController I call the following:
- (id)init {
self = [super init];
self.propertyArray = [NSArray new];
NSLog(#"init called");
return self;
}
The above does not print any values in NSLog. However, when I write :
- (id)initWithCoder:(NSCoder *)aDecoder {
self = [super initWithCoder:aDecoder];
NSLog(#"init called");
self.propertyArray = [NSArray new];
return self;
}
It does print "init called" in console. So my question is: why is the init method called and the other is not? Which one do I have to use, when i want to do my stuff before the view loads (and any other methods called)?
Any explanation will be appreciated, thanks.
To begin with, you mention ViewController in your question. A UIViewController's designated initializer is initWithNibName:bundle:
You would never want to override just init on a UIViewController.
There is a lifecycle for each object:
When initializing in code, you have the designated initializer. Which you can find in the documentation for that class. For NSObject derived classes this would be init:
- (id)init
{
self = [super init];
if (self) {
// perform initialization code here
}
return self;
}
All objects that are deserialized using NSKeyUnrchiving, which is what happens in the case of Storyboard's or NIBs(XIBs), get decoded. This process uses the initWithCoder initializer and happens during the unarchiving process:
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
// perform initialization code here
}
return self;
}
It is common, because of this lifecycle, to create a shared initializer that gets called from each initializer:
- (void)sharedInit
{
// do init stuff here
}
- (id)init
{
self = [super init];
if (self) {
[self sharedInit];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self sharedInit];
}
return self;
}
To take it one step further. In the case of Storyboard's and XIBs, if you want to perform initialization or updates AFTER the unarchiving is completed and to guarantee all your outlets and actions are connected, you would use awakeFromNib:
- (void)awakeFromNib
{
// do init or other stuff to be done after class is loaded from Interface Builder
}
When a class is instantiated in your code, you pick which initializer to call, depending on your needs. When a class is instantiated through framework code, you need to consult the documentation to find out what initializer would be called.
The reason that you see the behavior that you describe is that your view controller is in a storyboard. According to Cocoa documentation, when a view controller is instantiated through a storyboard, its initWithCoder: initializer is called. In general, this call is performed when an object gets deserialized.
Note that it is common to check the result of self = [super initWithCoder:aDecoder]; assignment, and skip further initialization when self is set to nil.
When you load view controller from nib file (and storyboard) it uses initWithCoder: so in your example this is why it call this method.
If you create your view controller programatically this method won't work and you should override initWithFrame: initialiser instead and also you should create view controller by calling
[[UIViewController alloc] initWithFrame:...];
The different inits are different constructors. As in any other language, an instance is instantiated by the most appropriate constructor. That's initWithCoder: when restoring from an archive.
As a style point, note that use of self.propertyArray in a constructor is considered bad form. Consider what would happen if a subclass overrode setPropertyArray:. You'd be making a method call to an incompletely instantiated object. Instead you should access the instance variable directly, and perform the idiomatic if(self) check to ensure it is safe to do so.

Setting delegate to MKMapView

I am new to iOS programming. I have created ViewController with MKMapView element, and I wanted to set delegate [mapView setDelegate:self]
First I done it in method initWithNibName:bundle: like:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[[self map] setDelegate:self]];
UITabBarItem *item = [[UITabBarItem alloc] init];
[item setTitle:#"Map"];
[self setTabBarItem:item];
}
return self;
}
In this case MKMapView did not send me any messages, but when I placed setting delegate message to viewDidLoad method, it worked fine.
Could someone explain me why it was not working when setting delegate message was in initWithNibName:bundle?
Views do not get loaded in initWithNibName, it just initializes your viewcontroller class and load the xib file which contains your view details.
When viewcontroller calls viewDidLoad, you will have all your view objects allocated and initialized.
In your case, when you setDelegate in initWithNibname, you are calling it on a nil value, so nothing get set, but in viewDidLoad mapView is allocated and initialized, so it works fine.
For a deeper insight refer:
http://developer.apple.com/library/ios/#featuredarticles/ViewControllerPGforiPhoneOS/ViewLoadingandUnloading/ViewLoadingandUnloading.html
Beautiful explanation here: What is the process of a UIViewController birth (which method follows which)?
Looking to understand the iOS UIViewController lifecycle
http://thejoeconwayblog.wordpress.com/2012/10/04/view-controller-lifecycle-in-ios-6/
This line is your problem:
[self map]
In initWithNibName the map is not yet initialized and it returns nil.
In viewDidLoad the map is already initialized.

Programmatic creation of NSView in Cocoa

i'm used to programming for iOS, and I've become very accustomed to the UIViewController. Now, i'm creating an OSX application and i'm having a few general questions on best practice.
In a UIViewController I generally setup my views in the -(void)viewDidLoad method - I don't actually create a custom UIView for the UIViewController unless it's really needed - so the UIViewController adds view to its own view, removes them, animates them and so forth - first off, is good practice?
And for my main question - what is the best practice in OSX? I like creating interfaces programatically and simply prefer it that way. If i, say create a new custom window and want to manage its view. What's the best way to do it, and where to i instantiate the user interface best?
Summary: How do i construct custom views programatically and set up a best-practice relationship between views and controllers in OSX? And is it considered good practice to use a view controller to create the views within its view?
Kind regards
To construct the view in code in an NSViewController, override loadView and be sure to set the view variable. Do not call super's implementation as it will attempt to load a nib from the nibName and nibBundle properties of the NSViewController.
-(void)loadView
{
self.view = [[NSView alloc] init];
//Add buttons, fields, tables, whatnot
}
For a NSWindowController, the procedure is very similar. You should call windowDidLoad at the end of your implementation of loadWindow. Also the window controller does not call loadWindow if the window is nil, so you will need to invoke it during init. NSWindowController seems to assume you will create the window in code before creating the controller except when loading from a nib.
- (id)initWithDocument:(FFDocument *)document
url:(NSURL *)url
{
self = [super init];
if (self)
{
[self loadWindow];
}
return self;
}
- (void)loadWindow
{
self.window = [[NSWindow alloc] init];
//Content view comes from a view controller
MyViewController * viewController = [[MyViewController alloc] init];
[self.window setContentView:viewController.view];
//Your viewController variable is about to go out of scope at this point. You may want to create a property in the WindowController to store it.
[self windowDidLoad];
}
Some optional fancification (10.9 and earlier)
Prior to 10.10, NSViewControllers were not in the first responder chain in OSX. The menu will automatically enable/disable menu items for you when an item is present in the responder chain. You may want to create your own subclass of NSView with an NSViewController property to allow it to add the controller to the responder chain.
-(void)setViewController:(NSViewController *)newController
{
if (viewController)
{
NSResponder *controllerNextResponder = [viewController nextResponder];
[super setNextResponder:controllerNextResponder];
[viewController setNextResponder:nil];
}
viewController = newController;
if (newController)
{
NSResponder *ownNextResponder = [self nextResponder];
[super setNextResponder: viewController];
[viewController setNextResponder:ownNextResponder];
}
}
- (void)setNextResponder:(NSResponder *)newNextResponder
{
if (viewController)
{
[viewController setNextResponder:newNextResponder];
return;
}
[super setNextResponder:newNextResponder];
}
Finally, I use a custom NSViewController that overrides setView to set the viewController property when I use my custom views.
-(void)setView:(NSView *)view
{
[super setView:view];
SEL setViewController = #selector(setViewController:);
if ([view respondsToSelector:setViewController])
{
[view performSelector:setViewController withObject:self];
}
}
- (BOOL)acceptsFirstResponder
{
return YES;
}
And for my main question - what is the best practice in OSX? I like
creating interfaces programatically and simply prefer it that way. If
i, say create a new custom window and want to manage its view. What's
the best way to do it, and where to i instantiate the user interface
best?
All these are done in awakeFromNib and init.
The following code is creating many windows and storing them in array. For each window you can add views. And each view may contains all the controls you wish to have.
self.myWindow= [[NSWindow alloc] initWithContentRect:NSMakeRect(100,100,300,300)
styleMask:NSTitledWindowMask
backing:NSBackingStoreBuffered
defer:NO];
[self.myWindowArray addObject:self.myWindow];
for (NSWindow *win in self.myWindowArray) {
[win makeKeyAndOrderFront:nil];
}

How to access subviews in View's initWithCoder method

I have a custom view which contains two UILabel. I want to customize their fonts before so I did that in initWithCoder method.
#implementation HomeTitleView
#synthesize ticketLabel;
#synthesize monthLabel;
- (id) initWithCoder:(NSCoder *)aDecoder{
self = [super initWithCoder:aDecoder];
if (self) {
[monthLabel setFont:[UIFactory getFontForKey:#"home_month"]];
[ticketLabel setFont:[UIFactory getFontForKey:#"home_ticket"]];
}
return self;
}
#end
Unluckily, this did not work. Using a debugger, I found that monthLabel and ticketLabel are both nil. Anyone has idea how can I solve this? What callback or method I should implement so that I can access both of my labels?
You can't do that. The views don't exist yet. They are instantiated when the loadView method is called, which happens automatically when the view property is first accessed. If you want to manipulate your views after they have loaded, the correct method to use is viewDidLoad.
Edit: That's assuming you are working with a UIViewController class. If you are working with a UIView class, you can use awakeFromNib or didAddSubview:.
Do you ever assign monthLabel and ticketLabel to UILabel? Something like:
self.monthLabel = [[[UILabel alloc] init] autorelease];
self.ticketLabel = [[[UILabel alloc] init] autorelease];
If so, can you update your post with the code?

Integration of QuickDialog with Storyboard

I am a new to iOS development, and I recently came across QuickDialog. From what it seems, it creates the dialog page for you automatically.
My recent learning has taught me to use the Storyboard to create the views. I was wondering, would QuickDialog integrate with Storyboard? So say I had a login form made by quick dialog, would the login view appear on the storyboard?
Thanks!
Your link seems broken. But I guess you are talking about this library?
Well, storyboard doesn't change much of the development environment. It just handles some transition between view controllers for you. So, yes, you can use QuickDialog with storyboard.
But it will not just appear in your storyboard. You need to add view controllers implemented with QuickDialog in it by yourself.
You have to create the QRootElement when storyboard is creating the controller in initWithCoder, and if you want to use the grouped option, it has to be set there, for the rest of the options, you can set them in the viewload, apart from that it's as usual:
Create a new class inheriting from QuickDialogController
Add in your class implementation the following code:
-(id) initWithCoder:(NSCoder *)aDecoder {
if ((self = [super initWithCoder:aDecoder])) {
QRootElement *_root = [[QRootElement alloc] init];
_root.grouped = YES;
/* Put your init code here or in viewDidLoad */
self.root = _root;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
QSection *section = [[QSection alloc] init];
QLabelElement *label = [[QLabelElement alloc] initWithTitle:#"Hello" Value:#"world!"];
[section addElement:label];
self.root.title = #"Hello World";
[self.root addSection:section];
}
Set the custom class of your storyboard UIViewController to be the one you just created

Resources