阻止其他程序员调用-init的最佳方法 [英] Best way of preventing other programmers from calling -init

查看:108
本文介绍了阻止其他程序员调用-init的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计类层次结构时,有时子类添加了一个新的 initWithSomeNewParam 方法,并且希望禁用对旧 init的调用从超类继承的方法。

When designing a class hierarchy, sometimes the subclass has added a new initWithSomeNewParam method, and it would be desirable to disable calls to the old init method inherited from the superclass.

首先,我已经阅读了问题这里,其中建议的替代方法是覆盖 init 以在运行时抛出异常,或覆盖并设置属性的默认值。在我的情况下,我不想提供默认值,我想清楚地表明不应该调用旧方法,而是应该使用带参数的新方法。

First of all, I've read the question here, where the proposed alternatives are either override init to throw an exception at runtime, or override and set default values for properties. In my case, I don't wan't to provide default values, and I want to clearly indicate that the old method should not be called, and instead the new method with parameters should be used.

因此运行时异常很好,但除非调试代码,否则团队中的其他程序员无法注意到旧方法不再用于使用。

So the runtime exception are fine, but unless the code is debugged, there's no way for other programmers in the team to notice that the old method is no longer intended to be used.

如果我没错,就无法将方法标记为私有。所以,除了添加评论之外,有没有办法做到这一点?

If I'm correct, there's no way to mark a method as "private". So, apart from adding comments, is there a way to do this?

提前致谢。

推荐答案

你可以明确标记你的 init 在头文件中不可用:

You can explicitly mark your init as being unavailable in your header file:

- (id) init __unavailable;

或:

- (id) init __attribute__((unavailable));

使用后面的语法,你甚至可以给出一个理由:

With the later syntax, you can even give a reason:

- (id) init __attribute__((unavailable("Must use initWithFoo: instead.")));

如果有人试图调用它,编译器会发出错误(不是警告)。

The compiler then issues an error (not a warning) if someone tries to call it.

这篇关于阻止其他程序员调用-init的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆