Why don't my inits run at startup?
Based on some examples, (primarily in Aaron's book) I had the idea that an overridden -init was somehow called at startup. When I tried it on my own, it didn't w开发者_StackOverflowork that way.
When I tried it out, I created a class Foo with an -init, with nothing in the ProjectAppDelegate class from NSObject that Xcode supplies and no IB. I expected it to somehow be called at startup.
Nothing happened. I think that it did nothing because nothing called my -init at startup. When I added a call to -init from ProjectAppDelegate, it ran correctly.
I'm wondering why the examples' -init method run at startup, and mine don't?
The init method of a class is called when the object is instantiated, meaning the object is created. Your Foo class would usually be instantiated like this:
Foo *myFoo = [[Foo alloc] init];
Before that point the class description is just that, a description. You could put the line in your app delegate's application:didFinishLaunchingWithOptions
method and it would indeed be initialized, at which point you could do something with myFoo.
init
is the conventional name for the method that initializes objects — for example, you create an NSMutableArray with [[NSMutableArray alloc] init]
. It will only be called at startup for objects that are created at startup. If you have code that you want to run when your program starts, you'd put it in your application delegate's applicationDidFinishLaunching
method.
精彩评论