Add the unavailable attribute to the header to generate a compiler error on any call to init.
- (instancetype) init __attribute__((unavailable("init not available")));
If you don't have a reason, just type __attribute__((unavailable))
, or even __unavailable
:
- (instancetype) __unavailable init;
Use doesNotRecognizeSelector: to raise a NSInvalidArgumentException. “The runtime system invokes this method whenever an object receives an aSelector message it can’t respond to or forward.”
- (instancetype) init {
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
Use NSAssert
to throw NSInternalInconsistencyException and show a message:
- (instancetype) init {
[self release];
NSAssert(false,@"unavailable, use initWithBlah: instead");
return nil;
}
Use raise:format:
to throw your own exception:
- (instancetype) init {
[self release];
[NSException raise:NSGenericException
format:@"Disabled. Use +[[%@ alloc] %@] instead",
NSStringFromClass([self class]),
NSStringFromSelector(@selector(initWithStateDictionary:))];
return nil;
}
[self release]
is needed because the object was already allocated. When using ARC the compiler will call it for you. In any case, not something to worry when you are about to intentionally stop execution.
In case you intend to disable init to force the use of a designated initializer, there is an attribute for that:
- (instancetype)myOwnInit NS_DESIGNATED_INITIALIZER;
This generates a warning unless any other initializer method calls myOwnInit internally. Details will be published in Adopting Modern Objective-C after next Xcode release (I guess).
Source: StackOverflow