Is there a method that is always called in Cocoa? Many classes have init
or initWith
, but even worse they can be loaded from a nib or something. I don't want to have to scrape around and find how it does this in this case. I just want to set some initial variables and other things, and I want a method to subclass that I can depend on no matter if it's a UIView
, UIViewController
or UITableViewCell
etc.
Whenever an object is "created" by default it is supposed to be done with myObject=[[MyObjectClass alloc]init] or the equivalent shortcut myObject=[MyObjectClass new] . That is where your init method is called.
init() Creates a date value initialized to the current date and time. iOS 7.0+ iPadOS 7.0+ macOS 10.9+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ Xcode 8.0+
No there is not such a method. init
comes from NSObject
so every object can use it, and as well subclasses define their own initialization methods. UIView
, for example, defines initWithFrame:
and furthermore there are init methods from protocols, such as NSCoding
which defines initWithCoder:
. This is the dynamic nature of objective-C, anything can be extended at any time. That being said, there are some patterns. UIViewController
almost always takes initWithNibName:bundle:
and UIView
almost always takes initWithFrame:
or initWithCoder:
. What I do is make an internal initialize method, and just have the other inits call it.
- (void)initialize
{
//Do stuff
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if(self)
{
[self initialize];
}
}
- (id)initWithCoder:(NSCoder *)aCoder
{
self = [super initWithCoder:aCoder];
if(self)
{
[self initialize];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With