What method is called before viewDidLoad() but after main? - objective-c

I observed that viewDidLoad() is called before didFinishLaunchingWithOptions() and I am looking for something where I can put some initialization code that has to be called before viewDidLoad().
Is there such a place?
Also, it is acceptable to recall viewDidLoad() from other place. It should be ok, or too risky?

You are wrong.
Place a NSLog directly under the method header and you will see that ViewDidLoad is directly called after.
[self.window addSubview:self.yourViewController.view];
So, you either use viewDidLoad or alternatively and not really beautiful you could use.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
This even gets called before ViewDidload

There's
- loadView()
Kicks in before viewDidLoad() and comes with an advice to never be called directly after that.
Here's the link to the apple docs.

I had a similar problem once that was caused when I added the view controller I wanted added to the window using the MainWindow.xib file.
To get around this, I assigned the window's rootViewController (you can also call addSubView, but assigning the rootViewController is better) in the didFinishLaunchingWithOptions: method of the app delegate. Once you do this you can easily put whatever logic you want in front or behind where this happens. It puts you in full control of when your view controller loads. In contrast, when the view controller is loaded via the nib, it's difficult to execute code in front of it (if at all possible). I know you sepecify the main xib in the app's plist, but I don't know if there is a way to run code before that nib is loaded.
In general I avoid adding the view controller in the xib for this reason.
My code looks more like:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// special pre load logic here...
UIViewController *myVC = [[MyAwesomeViewController alloc] init];
self.window.rootViewController = myVC;
[myVC release];
// special post load logic here...
[self.window makeKeyAndVisible];
return YES;
}

You may do your app initializations in viewDidLoad, however don't do any boundaries or size settings here, as they are not yet set.
Do them in viewDidLayoutSubviews, which is called after viewDidLoad.
I found this article, which was very helpful to me:
The UIViewController lifecycle

You could put initialization code in the init method of the class.
And it's fine to call viewDidLoad again from elsewhere. It's just like any other method.
EDIT:
It's fine to call viewDidLoad - but you should be careful with memory management. If you're allocating objects in viewDidLoad, calling it again will cause leaks. So, because of the typical functionality of viewDidLoad, you might want to pull the code out into another method that you'll call repeatedly and call from viewDidLoad.

Related

Correct method to present a different NSViewController in NSWindow

I am developing an app that is a single NSWindow and clicking a button inside the window will present a NSViewController, and a button exists in that controller that will present a different NSViewController. I know how to swap out views in the window, but I ran into an issue trying to do this with the multiple view controllers. I have resolved the issue, but I don't believe I am accomplishing this behavior in an appropriate way.
I originally defined a method in the AppDelegate:
- (void)displayViewcontroller:(NSViewController *)viewController {
BOOL ended = [self.window makeFirstResponder:self.window];
if (!ended) {
NSBeep();
return;
}
[self.box setContentView:viewController.view];
}
I set up a target/action for an NSButton to the AppDelegate, and here's where I call that method to show a new view controller:
- (IBAction)didTapContinue:(NSButton *)sender {
NewViewController *newVC = [[NewViewController alloc] init];
[self displayViewcontroller:newVC];
}
This does work - it presents the new view controller's view. However if I then click any button in that view that has a target/action set up that resides within its view controller class, the app instantly crashes.
To resolve this issue, I have to change didTapContinue: to the following:
- (IBAction)didTapContinue:(NSButton *)sender {
NewViewController *newVC = [[NewViewController alloc] init];
[self.viewControllers addObject:newVC];
[self displayViewcontroller:[self.viewControllers lastObject]];
}
First of all, can you explain why that resolves the issue? Seems to be related to the way the controller is "held onto" in memory but I'm not positive.
My question is, how do I set this up so that I can swap out views from within any view controller? I was planning on getting a reference to the AppDelegate and calling displayViewcontroller: with a new controller I just instantiated in that class, but this causes the crash. I need to first store it in the array then send that reference into the method. Is that a valid approach - make the viewControllers array public then call that method with the lastObject, or how should this be set up?
What is interesting in your code is that you alloc/init a new view controller every time that you call the IBAction. It can be that your view its totally new every time you call the IBAction method, but I would think that you only have a limited number of views you want to show. As far as my knowledge goes this makes your view only to live as long as your IBAction method is long. That the view still exists, is because you haven't refreshed it. However, calling a method inside a view controller that is not in the heap anymore (since you left the IBAction method and all local objects, such as your view controller are taken of the heap thans to ARC) makes the app crash, because you reference a memory space that is not in use or used by something else.
Why does the app work when you ad the view to the viewcontrollers array? I assume this array is an array that has been initiated in the AppDelegate and now you add the view controller with a strong reference count to the viewcontrollers array. When you leave the IBAction method, the view controller still has a strong reference and ARC will not deallocate the view controller.
Is this the proper way? Well, it works. I would not think it is considered very good programming, since you don't alloc/init an object in a method that needs to stay alive after leaving the method. It would be better practice to allocate and initialize your view controller(s) somewhere in an init, awakeFromNIB or a windowDidLoad method of your AppDelegate. The problem with your current solution is that you are creating an endless array of view controllers of which you only use the last. Somewhere your program will feel the burden of this enormously long array of pretty heavy objects (view controllers) and will run out of memory.
Hope this helps.
By the way, this is independent of whether you use Mavericks or Yosemite. I was thinking in a storyboard solution, but that wouldn't answer your question.
Kind regards,
MacUserT

Xcode: Document-based app window is not loading during attempt to subclass NSWindowController

I really haven't done much and i'm already stuck.
So far i've done:
added NSWindowController subclass (MikesWindowController.h & .m)
removed windowNibName from MikesDocument.m (since i'm implementing my own
WindowController subclass.)
I tried:
Tested if NSLog would come back at init, windowControllerDidLoadNib, applicationDidFinishLaunching. Only the NSLog at init printed.
And, tested the Main Menu -> File -> New after after compiling my Document app.
Am I implementing this right? Thanks. Any suggestions would be great! Under MikesDocument.m
-(void)makeWindowControllers{
MikesController *controller = [[MikesWindowController alloc]init];
[self addWindowController:controller];
}
After much deliberation I found that answer. Woohoo. Enjoy future.
removed initWithWindow from my NSWindowController subclass
implemented initWithWindowNibName to my NSWindowController subclass so now anytime I initialize I must specify the window nibName.
Below I implemented initWithWindowNibName in my NSWindowController subclass heres what it looks like:
MikesWindowController.m
-(id) initWithWindowNibName:(NSString *)windowNibName{
self = [super initWithWindowNibName:windowNibName];
return self;
}
(Below) Back again to the main document I corrected the makeWindowController method and instantiated my controller with "MikesDocument" (for MikesDocument.xib) and added it.
MikesDocument.m
-(void)makeWindowControllers{
MikesWindowController *controller =
// must tell controller which nib file to use.
[[MikesWindowController alloc]initWithWindowNibName:#"MikesDocument"];
[self addWindowController:controller];
}
Success! Don't even bother calling init or implementing init as it returns an error at any time.

NSTextField set cursor

Okay so I feel like there's something obvious I'm missing in this question. I've used makeFirstResponder throughout my code to move from textField 1 to 2, 2 to 3, etc. That seems to work as I want it to, yet when the new view is loaded, I want the cursor to be in textField1, and yet the following code does not place the cursor in textField1 upon load.
- (void) awakeFromNib{
[[[self view] window] makeFirstResponder:textField1];
}
I also tried setInitialFirstResponder, and that didn't have any effect either (I don't even think that would be right.) So, is it because it is in the awakeFromNib method? Can anyone tell me what I'm missing? Thanks in advance.
EDIT - My solution was differed slightly from the accepted answer so I thought I'd post my implementation. Because the view I wanted to set the first responder for was a subview added later (think the second screen of an application wizard), I simply added a setCursorToFirstTextField method:
- (void) setCursorToFirstTextField {
[[[self view] window] makeFirstResponder:textField1];
}
And made sure to call it after I had added the subview to the custom view on the original window.
Yes, you're right about the problem being the location of the method in awakeFromNib. If you log [self.view window] in your awakeFromNib, you'll see that it's NULL. I don't know how exactly you have things set up, but I'm guessing (if this relates to your WizardController question) that you're doing an alloc initWithNibName:bundle: in another class to create your view controller and then adding that controller's view to the view hierarchy. If you throw some logs in there, it will show you that awakeFromNib in the controller class is called after the alloc init, but before the view is added as a subview, so there is no window at that time. The way I got around this problem was to create a setup method in the view controller class (with the makeFirstResponder code in it), and call it from the class where you create the controller after you add it as a subview.
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
self.wizard = [[WizardController alloc] initWithNibName:#"WizardController" bundle:nil];
[self.window.contentView addSubview:wizard.view];
[self.wizard doSetup];
}

is it a good idea to call viewdidload in a method?

I was just curious weather it is a good idea to call viewdidload a method like in an ibaction or something of that kind.
thanks,
TC
Check:
UIViewController Class Reference
viewDidLoad
This method is called after the view
controller has loaded its associated
views into memory. This method is
called regardless of whether the views
were stored in a nib file or created
programmatically in the loadView
method. This method is most commonly
used to perform additional
initialization steps on views that are
loaded from nib files.
The viewDidLoad method is automatically triggered.
Generally there is no need to trigger viewDidLoad yourself.
If you need to run specific code both after loading and button-click, do this:
- (void)viewDidLoad {
[self specificFunction];
}
- (IBAction)theButton:(id)sender {
[self specificFunction];
}
- (void)specificFunction {
// This code wil run after the view has been loaded
// and when the user clicks the button
}
The disadvantage of calling ViewDidLoad is , the superclass methods would be called as it has [super viewDidLoad], which is not a good idea .
It's better to have a separate methods and call them whenever necessary .

UIViewController not loading my custom UIView

This should be straight forward for a guru. I don't have any code really written out, just a couple of controllers and a custom UIView. All connected through nibs. The app loads without crashing, yet I can't see my NSLog() hit from my custom UIView.
My application delegate has default template code which calls for a class of mine called TabAnimationController. TabAnimationViewController has its view set to TabView. I made sure that in TabAnimationViewController's NIB that File's owner is set to TabAnimationViewController and that my instance of UIView has its class set to TabView.
In TabView.m I'm trying to see how NSLog is going to hit, and it's not showing up at all.
- (void)loadView {
NSLog(#"calling loadView");
}
- (id)initWithFrame:(CGRect)frame {
NSLog(#"Calling initWithFrame:");
return self;
}
Strange. I'm not sure why even after proper IB connections that my NSLog will not show up. Only anything put into drawRect: will invoke. Why isn't initWithFrame or loadView ever get hit? What if I want to customize this view programmatically?
First of all, when a view is dehydrated from nib file, instead of initWithFrame, initWithCoder is invoked. So you need to implement your initialization in initWithCoder as well. (It may be a good idea to keep the initWithFrame initialization as well, if you anticipate programmatically creating your TabView instead of hooking up in the IB. Just refactor your initialization to another method and call it from both implementations.)
Also in your initialization code above you must always call the super class's initialization. There is a boiler plate pattern all custom classes use in their init implementation for that:
if (self = [super initXXX]) { do your initialization }
return self;
Second, loadView which is actually a UIViewController method and not a UIView method is invoked only if the view outlet of the controller is nil.
Unless you are composing your view yourself programmatically using your controller, you do not need to override loadView. Instead you should override viewDidLoad, which is called after the view is loaded, to do additional initialization.
The simplest way to get this up and running is simply to use the "View based Application" template when you create a new project. It sets up everything you need to start with.
But, in short, you're looking at the wrong methods. First, you shouldn't override loadView unless you're creating your view programatically. If it's loading from a XIB file look at the initWithNibName method.
You might also want to look at the viewDidLoad, viewWillAppear and viewDidAppear methods that are triggered, well, it's fairly obvious when!