Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a init method in iOS that is always called?

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.

like image 728
napierzaza Avatar asked Aug 01 '12 01:08

napierzaza


People also ask

How do you call an init method in Objective C?

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.

What is INIT in Xcode?

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+


1 Answers

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];
    }
}
like image 72
borrrden Avatar answered Nov 15 '22 04:11

borrrden