简体   繁体   English

如何防止在 Objective-C 中使用我的自定义方法以外的其他初始化方法

[英]How to prevent usage of other init methods other than my custom method in Objective-C

Background - in my iPhone app I have a custom UITableViewController - I was going to pass some required config to it by extending the existing "(id)initWithStyle:(UITableViewStyle)style" method to an extended custom one.背景 - 在我的 iPhone 应用程序中,我有一个自定义 UITableViewController - 我将通过将现有的“(id)initWithStyle:(UITableViewStyle)style”方法扩展为扩展的自定义方法,将一些必需的配置传递给它。

Question - what's the best way to ensure that the user of this custom controller class can only call my custom init method, and not initWithStyle or any other init methods?问题 - 确保此自定义 controller class 的用户只能调用我的自定义 init 方法,而不是 initWithStyle 或任何其他 init 方法的最佳方法是什么?

I usually document this and put a [self doesNotRecognizeSelector:_cmd] call into the init methods that are not intended to be used.我通常对此进行记录,并将[self doesNotRecognizeSelector:_cmd]调用放入不打算使用的 init 方法中。

In conjunction, marking the method deprecated (see How do I flag a function as being deprecated in an iPhone Objective C header file? ) prevents runtime suprises and gets you a warning at compile time.同时,将方法标记为已弃用(请参阅如何在 iPhone 目标中将 function 标记为已弃用 C header 文件会导致编译时出现警告)。

You can override the init methods that you don't want to be used, and raise an exception there.您可以覆盖您不想使用的 init 方法,并在那里引发异常。

You can also override them and make them initialize with the designated initializer.您还可以覆盖它们并使用指定的初始化程序进行初始化。

Also, you should specify it on your documentation.此外,您应该在文档中指定它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM