是否有一个 Objective-C 等同于 Swift 的 fatalError?

Is there an Objective-C equivalent to Swift's fatalError?

我想放弃超类的默认初始化 method.I 可以通过 Swift 中的 fatalError 轻松实现:

class subClass:NSObject{
  private var k:String!

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

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

如何在 Objective-C 中完成?

您可以在这种情况下提出异常。像这样:

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

只需调用NSObjectdoesNotRecognizeSelector:方法。你会写:

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

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

NSAssert(NO, @"balabala");

- (instancetype)init NS_UNAVAILABLE;

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

感谢@Cœur

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

最佳答案是我的 ;-)

当执行遇到 FatalError 时,您会 Xcode 显示遇到 FatalError 的行 — 并在日志 window 中显示有关文件、行号等的信息。

如果您想要相同的行为,您必须通过包含 "assert.h"

使用标准 os 库中可用的 "assert"
#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.

最佳做法是在 .h 中声明:

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

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