Skip to content

Common Initializers #5

Description

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions