Disabling init
Sometimes you just don't want to support init
Sometimes you don’t want to support init
, or another method. How best do you do it?
In the old days you would be to catch it in runtime; call [self release]
, error, then return nil. This approach should no longer be used. It leaves a ticking timebomb waiting for somebody, quite possibly a later version of yourself, to call it and blow everything up.
Since macOS 10.7 and iOS 5 NSObjCRuntime.h
has included NS_UNAVAILABLE
. An easy to use macro wrapper of the unavailable __attribute__
. This is great as it provides a compile time error when the method is used, preventing any issue from ever even reaching runtime.
@interface SomeClass : NSObject
// ...
- (instancetype)init NS_UNAVAILABLE;
// ...
@end
More generally, you can use this to cause a compile error for any method you need it to.
Swift
Apple has also conveniently added NS_SWIFT_UNAVAILABLE
to allow you to disable Objective-C methods in Swift.
License
Any source in this article is released under the ISC License.