是否可以在Objective-C中将-init方法设为私有? [英] Is it possible to make the -init method private in Objective-C?

查看:92
本文介绍了是否可以在Objective-C中将-init方法设为私有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Objective-C中隐藏(私有化)我的课程的-init方法.

I need to hide (make private) the -init method of my class in Objective-C.

我该怎么做?

推荐答案

与Smalltalk一样,Objective-C也没有私有"方法与公共"方法的概念.任何消息都可以随时发送到任何对象.

Objective-C, like Smalltalk, has no concept of "private" versus "public" methods. Any message can be sent to any object at any time.

如果调用了-init方法,您可以做的是抛出NSInternalInconsistencyException:

What you can do is throw an NSInternalInconsistencyException if your -init method is invoked:

- (id)init {
    [self release];
    @throw [NSException exceptionWithName:NSInternalInconsistencyException
                                   reason:@"-init is not a valid initializer for the class Foo"
                                 userInfo:nil];
    return nil;
}

另一种方法-在实践中可能要好得多-尽可能使-init对您的班级有意义.

The other alternative — which is probably far better in practice — is to make -init do something sensible for your class if at all possible.

如果由于要确保"使用单例对象而尝试执行此操作,请不要打扰.具体来说,不要理会创建单例的覆盖+allocWithZone:-init-retain-release"方法.实际上,这几乎是不必要的,只是增加了复杂性而没有真正的明显优势.

If you're trying to do this because you're trying to "ensure" a singleton object is used, don't bother. Specifically, don't bother with the "override +allocWithZone:, -init, -retain, -release" method of creating singletons. It's virtually always unnecessary and is just adding complication for no real significant advantage.

相反,只需编写代码,使您的+sharedWhatever方法成为访问单例的方式,并将其记录为在标头中获取单例实例的方式.在绝大多数情况下,这就是您所需要的.

Instead, just write your code such that your +sharedWhatever method is how you access a singleton, and document that as the way to get the singleton instance in your header. That should be all you need in the vast majority of cases.

这篇关于是否可以在Objective-C中将-init方法设为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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