objc-guide icon indicating copy to clipboard operation
objc-guide copied to clipboard

Common Initializers

Open markavitale opened this issue 5 years ago • 0 comments

Convention

When there is more than one way to init an object (e.g. initWithFrame, initWithCoder) and these perform common routines (such as setting ivars, sizing, etc.), consider using c-style function to perform to handle this vs. an Obj-C function.

Rationale

Particularly if the name is a common one (e.g. initCommon:, etc.), there is some risk that the function could be overridden without calling super.

Example

@implementation XYZView

void XYZCommonInit(XYZView *self) {
  // ...
}

- (instancetype)initWithFrame:(CGRect)frame {
    // ...
   XYZCommonInit(self);
   return self;
}
- (instancetype)initWithCoder:(NSCoder *)coder {
    // ...
   XYZCommonInit(self);
   return self;
}
@end

Note: Could put a bit of discussion in the rationale about how this truly applies to any private selector but in practice we have hit the common initializer case more than anything else. We can even add that if shipping a framework, private functionality of anything publicly exposed for subclassing should potentially avoid private selectors and stick to C-style functions to prevent clients of your framework from unintentionally overriding private functionality.

markavitale avatar Jun 05 '20 05:06 markavitale