Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start with init method or not?

i was wondering when we use the "init" method in a project? i have seen many projects without it, they used "applicationDidFinishLaunching" to start the application, but not the init method, do you have any idea about that?

Thanks a lot

like image 380
Paul Avatar asked Oct 11 '22 12:10

Paul


2 Answers

The init method is used to initialize an object after allocating it. In case it is not defined, then the base class implementation is called, as with any other method in Objective-C, and if the base class has got no init method, then the base class' base class' init will be called, and so on, up to the NSObject's init which is for sure provided.

If you don't declare an init method, then you will not be able to properly initialize the ivars in your class, if any.

About applicationDidFinishLaunching, this is a method for a very special class that any Cocoa/iOS application has got, its application delegate. For example:

 @interface myAppDelegate : NSObject <UIApplicationDelegate> {
 ...
 }

(N.B.: UIApplicationDelegate could be as well NSApplicationDelegate)

As you see, this class derives from NSObject, so, it will be inited by the framework by calling an init method defined in that class (which one specifically depends on the framework). Then, at some point, the framework will call the applicationDidFinishLaunching method and you have a change to initialize all your delegates' members and do whatever you need to start your app up.

In this case, the fact that you are not required to do initialization in an init method but in applicationDidFinishLaunching is related to a specific pattern of interaction between your UIApplication (or NSApplication) object and its delegate. This pattern was defined by Apple in this way;

  1. you specify your application delegate class either in your MainWindow.xib or when calling UIApplicationMain in main.c;

  2. the framework is responsible to instantiate those class (in a custom way that programmers do not need to deal with) and call applicationDidFinishLaunching so that you can do whatever you need with it.

I hope this explanation helps you understanding what is going on with the app delegate and why you do not declare an init method.

like image 172
sergio Avatar answered Oct 13 '22 03:10

sergio


Implementing init method is not necessary unless you want to do some custom initialization.

Doc says,

Subclasses should override the init method to add class-specific initialization code. Subclass versions of init need to incorporate the initialization code for the classes they inherit from, through a message to super:

like image 31
EmptyStack Avatar answered Oct 13 '22 03:10

EmptyStack