- Why is it important to call the
- (id) init
method? - How should I call it, is there anything special required?
- When should I call this method?

- 124,188
- 49
- 220
- 267

- 134
- 2
- 10
2 Answers
Why?
-(id)init
is called to initialize the variables inside an object and do any necessary setup (it's basically the constructor).
How?
Obj *obj = [[Obj alloc] init];
When?
Whenever you want to create an object.
Before calling init, you need to call alloc on the class, so that the necessary memory is allocated for an object of that type.
-(id)init
is the designated constructor of an object. Some classes have other designated constructors, for example UIViewController, which uses initWithNibName:bundle:
.
-
Thanks Goetz.I can get it.But even though i dont create an object for AppDelegateclass(the class which is automatically generated) how is the -(id)init method executed...?? – iphone66 Feb 03 '11 at 14:30
-
The AppDelegate is instantiated at some point from the function call NSApplicationMain (which is called inside the main function in main.m, you can find this file in "Other Sources"). Usually, you don't overwrite init for the AppDelegate, but use applicationDidFinishLaunching: do initialize the application. – goetz Feb 03 '11 at 14:55
-
Specifically, the app delegate is frequently in the MainMenu nib (and I think it is this way in all Cocoa and Cocoa Touch project templates now). The app delegate is thus instantiated by unarchiving the nib. If it's not in the nib, then `NSApplicationMain`/`UIApplicationMain` alone will not instantiate the app delegate; you must do it yourself in code in the `main` function. – Peter Hosey Feb 03 '11 at 16:41
http://www.otierney.net/objective-c.html:
[object init]
is the constructor call, which initializes any variables in the object. This method is called on the instance returned from[Fraction alloc]
. This operation is so common it's usually just done in one line asObject var = [[Object alloc] init];

- 124,188
- 49
- 220
- 267

- 6,975
- 3
- 38
- 60