创建一个没有 init 方法的类 (Objective-c) [英] Creating a class with no init method (Objective-c)
问题描述
是否可以创建一个没有 init 方法的类来强制所有调用者使用工厂方法创建对象?
Is it possible to create a class with no init method so as to force all callers to create the object with a factory method instead?
推荐答案
所以基本上,您希望确保您的类永远不会使用 -init 进行初始化,对吗?你不能完全做你想做的事,但你可以接近.
So basically, you want to make sure that your class is never initialized using -init, right? You can't do exactly what you want to do, but you can come close.
由于您是从 NSObject 继承的,因此您有一个 init 方法,并且您无法阻止它被调用.也就是说,您可以将 init 覆盖为:
Since you inherit from NSObject, you have an init method and there's nothing you can do to prevent it from being called. That said, you could override init to this:
- (id)init
{
[self dealloc];
@throw [NSException exceptionWithName:@"MyExceptionName" reason:@"Reason" userInfo:nil];
return nil;
}
这样,无论何时有人调用您的 -init 方法,它都会杀死该对象,因此实际上,您的 init 方法几乎是不可调用的.
This way, anytime someone calls your -init method, it kills the object, so practically speaking, your init method is pretty much un-callable.
这篇关于创建一个没有 init 方法的类 (Objective-c)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!