27

I want to discard superclass's default init method.I can achieve this easily with fatalError in Swift:

class subClass:NSObject{
  private var k:String!

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

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

How can I do it in Objective-C?

wj2061
  • 6,778
  • 3
  • 36
  • 62

5 Answers5

55

You can raise an exception in this case. Something like this:

[NSException raise:@"InitNotImplemented" format:@"Subclasses must implement a valid init method"];
pkamb
  • 33,281
  • 23
  • 160
  • 191
Shripada
  • 6,296
  • 1
  • 30
  • 30
  • 1
    Be careful with `NSAssert` as the value of `NS_BLOCK_ASSERTIONS` can alter its behavior and cause it to not throw in production code resulting in no assertion validation. – Matt Robinson Jun 14 '19 at 18:35
  • Oh, yes, didnt think about this. will edit the answer – Shripada Jun 17 '19 at 03:47
6
NSAssert(NO, @"balabala");

or

- (instancetype)init NS_UNAVAILABLE;

========== Update ==========

Thanks to @Cœur

NSAssert is disabled by default in production, which is different with FatalError. NSException is better.

enter image description here

hstdt
  • 5,652
  • 2
  • 34
  • 34
6

Best practice is to declare in the .h:

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

Then the compiler won't compile if anyone calls it.

scaly
  • 509
  • 8
  • 18
4

Just call NSObject's doesNotRecognizeSelector: method. You would write:

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

where _cmd is the hidden parameter to every method whose value is the selector of the method.

Koen.
  • 25,449
  • 7
  • 83
  • 78
CRD
  • 52,522
  • 5
  • 70
  • 86
0

The best answer is mine ;-)

When execution meets a FatalError you got Xcode to display the line where FatalError has been meet — and display info about file, line number and so on, in the log window.

If you want the same behavior you must use "assert" available in standard os Libs by including "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.
Luc-Olivier
  • 3,715
  • 2
  • 29
  • 29