简体   繁体   中英

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.

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];
    }
}

Not 100% sure that it is always called, but I am pretty sure that this is a viable option. To be perfectly honest, I can't recall that I have ever seen this method used in practice and I usually shy away from using this method (I have absolutely no idea why, probably because it's just not the cleanest and most comprehensive method to achieve this...):

-didMoveToSuperview()

From documentation:

Tells the view that its superview changed. The default implementation of this method does nothing. Subclasses can override it to perform additional actions whenever the superview changes.

There's many ways you can write a custom initializer.

- (id)initWithString:(NSString *)string {
    if((self == [super init])) {
        self.string = string;
    }
    return self;
}

That's just how I write my initializers in general. For example, the one above takes a string. (you don't have to pass strings if you don't want).

Btw, init is a method. According to the header for NSObject, init has a method implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM