问题描述
这被认为是典型的
- (id)init {
self = [super init];
if (self) {
// <#initializations#>
}
return self;
}
但是最好不要这样做
- (id)init {
self = [super init];
if (self) {
// <#initializations#>
} else {
@throw [NSException exceptionWithName:NSInternalInconsistencyException reason:@"you think your constructor is executing, but it's not"] userInfo:nil]
}
return self;
}
这个问题的推论是under什么条件会 [super init]
return nil
和 $ c> init 方法?
The corollary to this question is, "under what conditions would [super init]
return nil
and shouldn't you handle that in the init
method?"
推荐答案
,JustSid的意思是:
One reason, why you should do, what JustSid is saying:
在面向对象的设计中,你应该总是编写代码,好像你可能会把你的类交给另一个开发者的另一个项目。所以你不能假设,他的项目中的初始化失败可能是坏的,因为它可能在你的。也许这个开发者是你在5年。想象一下你的麻烦来修复你的200个类,你想重用。
In object-orientated design you should always code, as if you maybe will hand your class over to another project by another developer. So you can't assume, that a failure in initialization in his project may be as bad as it is probably in yours. Maybe this developer is you in 5 years. Imagine your hassle to fix your 200 classes, you want to reuse.
这篇关于为什么不抛出异常,如果[super init]返回nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!