问题描述
我需要在 Objective-C 中隐藏(设为私有)我的类的 -init
方法.
I need to hide (make private) the -init
method of my class in Objective-C.
我该怎么做?
推荐答案
Objective-C 与 Smalltalk 一样,没有私有"方法与公共"方法的概念.任何消息都可以随时发送给任何对象.
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.
如果您尝试这样做是因为您试图确保"使用单例对象,请不要打扰.具体来说,不要理会override +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 方法设为私有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!