NS_UNAVAILABLE
- (instancetype)init NS_UNAVAILABLE;
这是不可用属性的简短版本。它首先出现在 macOS 中 10.7 和 iOS 5。它在 NSObjCRuntime.h 中定义为#define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE。
有一个版本是disables the method only for Swift clients,不适用于ObjC代码:
- (instancetype)init NS_SWIFT_UNAVAILABLE;
unavailable
将unavailable 属性添加到标头以在任何对init 的调用中生成编译器错误。
-(instancetype) init __attribute__((unavailable("init not available")));
如果你没有理由,只需输入__attribute__((unavailable)),甚至是__unavailable:
-(instancetype) __unavailable init;
doesNotRecognizeSelector:
使用doesNotRecognizeSelector: 引发 NSInvalidArgumentException。 “只要一个对象接收到它无法响应或转发的 aSelector 消息,运行时系统就会调用此方法。”
- (instancetype) init {
[self release];
[super doesNotRecognizeSelector:_cmd];
return nil;
}
NSAssert
使用NSAssert 抛出 NSInternalInconsistencyException 并显示一条消息:
- (instancetype) init {
[self release];
NSAssert(false,@"unavailable, use initWithBlah: instead");
return nil;
}
raise:format:
使用raise:format: 抛出你自己的异常:
- (instancetype) init {
[self release];
[NSException raise:NSGenericException
format:@"Disabled. Use +[[%@ alloc] %@] instead",
NSStringFromClass([self class]),
NSStringFromSelector(@selector(initWithStateDictionary:))];
return nil;
}
需要[self release],因为该对象已经allocated。使用 ARC 时,编译器会为您调用它。无论如何,当您要故意停止执行时,不必担心。
objc_designated_initializer
如果您打算禁用 init 以强制使用指定的初始化程序,则有一个属性:
-(instancetype)myOwnInit NS_DESIGNATED_INITIALIZER;
这会产生一个警告,除非任何其他初始化方法在内部调用 myOwnInit。下一次 Xcode 发布后会在Adopting Modern Objective-C 发布详细信息(我猜)。