iOS: UIView subclass init or initWithFrame:?

后端 未结 3 1745
谎友^
谎友^ 2020-12-07 13:10

I made a subclass of UIView that has a fixed frame. So, can I just override init instead of initWithFrame:? E.g.:

- (i         


        
3条回答
  •  囚心锁ツ
    2020-12-07 13:35

    In an Objective-C class with multiple initialisers, the designated initialiser is the one that does the meaningful work. So, often you have a class with a few initialisers, say:

    - (id)initWithRect:(CGRect)someRect;
    
    - (id)initWithRect:(CGRect)someRect setDefaultColour:(BOOL)setDefaultColour;
    
    - (id)initWithRect:(CGRect)someRect setDefaultColour:(BOOL)setDefaultColour
                 linkTo:(id)someOtherObject;
    

    In that case you'd normally (but not always) say that the third was the designated initialiser, and implement the other two as e.g.

    - (id)initWithRect:(CGRect)someRect
    {
        return [self initWithRect:someRect setDefaultColour:NO];
    }
    
    - (id)initWithRect:(CGRect)someRect setDefaultColour:(BOOL)setDefaultColour
    {
        return [self initWithRect:someRect setDefaultColour:setDefaultColour
                       linkTo:nil];
    }
    

    If a class has only one initialiser then that's the designated initialiser.

    In your case to follow best practice you should implement initWithFrame: and also a vanilla init: that calls initWithFrame: with your normal dimensions. The normal convention is that you can add new variations on init in subclasses, but shouldn't take any away, and that you always do the actual initialising work in the designated initialiser. That allows any initialising methods from the parent class that you don't provide new implementations of still to work appropriately with your subclass.

提交回复
热议问题