I am creating a subclass of UIBarButtonItem, to provide some specific functionality.
The new class has an initializer, that is the only one that should be used when creating an instance of the class:
- (id) initWithSomeObject:(SomeObject *)param;
The problem is, all the initializers from UIBarButtonItem are still available, so I could create an instance of my new class using something like
MyCustomUIBarButtonItem *button = [[MyCustomUIBarButtonItem alloc] initWithBarButtonSystemItem:systemItem target:target action:action];
or something else...
Is there a way to hide the initializers from UIBarButtomItem in my subclass, so that they cannot be used?
Just document it clearly that no other initialiser but that one should be used.
If you really don't trust your fellow developers or yourself to read the documentation, you can also override the other initialisers and put NSAssert(NO,@"Don't use this");
in the body. You can throw an exception instead of using an assertion.
You can't make private the other initializers; nothing is private in Obj-C. As freespace suggests, the best you can do here is document it and if you really need to, throw exceptions out of the other initializers.
If this seems horrendously error-prone, that's because it is. The initializer cluster pattern with one "designated" one (which there is no syntactical support for) is a fault in the language or Cocoa framework/pattern design, depending on how you look at it.
精彩评论