开发者

Override inherited method as private in objective-c [duplicate]

开发者 https://www.devze.com 2023-01-07 06:15 出处:网络
This question already has answers here: Is it possible to make the -init method private in Objective-C?
This question already has answers here: Is it possible to make the -init method private in Objective-C? 开发者_JAVA百科 (9 answers) Closed 9 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消