I don’t plan to write applications without IB, I’m just in the process of trying to learn more about programming.
How can I get a single instance of my AppController class at startup? (It’s normally loaded from the nib.) And can you clear up the use of +initialize and -init? If I understand, +initialize is called on all classes at startup. How can I use this to create an instance of my AppController with instance variables that make up my interface?
Hope that makes sense, and thanks for any help.
+initalizeis sent to a class the first time it or one of its subclasses receives a message for the first time. So, when you do:That
allocmessage triggersinitialize.If you do the same thing with a subclass:
That
allocmessage will trigger+[YourClass initialize]the same way the other one did (prior to also triggering+[SubclassOfYourClass initialize]. But only one of these will do it—each class’sinitializenever gets called more than once. (Unless you call it yourself with[super initialize]or[SomeClass initialize]—so don’t do that, because the method won’t be expecting it.)-init, on the other hand, initializes a new instance. In the expression[[YourClass alloc] init], you are personally sending the message directly to the instance. You may also call it indirectly, through another initializer ([[YourClass alloc] initWithSomethingElse:bar]) or a convenience factory ([YourClass instance]).Unlike
initialize, you should always sendinit(or another initializer, if appropriate) to your superclass. Most init methods look roughly like this:Details differ (this method or the superclass’s or both may take arguments, and some people prefer
self = [super init]on its own line, and Wil Shipley doesn’t assign toselfat all), but the basic idea is the same: call[super init[WithSomething:…]], make sure it didn’t returnnil, set up the instance if it didn’t, and return whatever the superclass returned.This implies that you can return
nilfrominit, and indeed you can. If you do this, you should[self release], so that you don’t leak the failed object. (For detecting invalid argument values, an alternative isNSParameterAssert, which throws an exception if the assertion fails. The relative merits of each are beyond the scope of this question.)The best way is to do it all in
main:You’ll do any other set-up in your application delegate methods in
AppController.You already know this, but for anyone else who reads this: Nibs are your friend. Interface Builder is your friend. Don’t fight the framework—work with it, and build your interface graphically, and your application will be better for it.