Objective-C中是否有类似于Swift的fatalError的方法?

27

我想放弃父类的默认初始化方法。在 Swift 中,我可以使用 fatalError 轻松实现:

class subClass:NSObject{
  private var k:String!

  override init(){
    fatalError("init() has not been implemented")
  }

  init(kk:String){
    k = kk
  }
}    

我该如何用Objective-C实现它?

5个回答

55

在这种情况下,您可以引发异常。像这样:

[NSException raise:@"InitNotImplemented" format:@"Subclasses must implement a valid init method"];

1
在使用NSAssert时要小心,因为NS_BLOCK_ASSERTIONS的值可能会改变其行为,并导致在生产代码中不抛出断言验证,从而导致没有断言验证。 - Matt Robinson
哦,是的,没有考虑到这一点。我会编辑答案。 - Shripada

6
NSAssert(NO, @"balabala");

或者
- (instancetype)init NS_UNAVAILABLE;

========== 更新 ==========

感谢 @Cœur

NSAssert在生产环境中默认是禁用的,这与FatalError不同。使用NSException更好。

enter image description here


1
请查看Matt Robinson关于NSAssert的评论。 - Cœur

6

最佳实践是在.h文件中声明:

(instancetype)init __attribute__((unavailable("init() is unavailable")));

那么如果有人调用它,编译器就不会编译。


4

只需调用NSObjectdoesNotRecognizeSelector:方法。你可以这样写:

- (instancetype) init
{
    [self doesNotRecognizeSelector:_cmd];
}

其中_cmd是每个方法的隐藏参数,其值为该方法的选择器。


0

最佳答案是我的 ;-)

当执行遇到致命错误时,你可以让Xcode显示FatalError所在的行,并在日志窗口中显示有关文件、行号等信息。

如果您想要相同的行为,您必须使用标准os库中提供的"assert",并包括"assert.h"。

#include "assert.h"

printf("Assertion false: blah, blah\n");
assert(false);

>>Assertion false: blah, blah
>>Assertion failed: (false), function +[X Y], file /Development/Tests/TestAssert.m, line 32.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接