objective-c - 是否可以在 Objective-C 中将 -init 方法设为私有(pr

我需要在 Objective-C 中隐藏(设为私有(private))我的类的 -init 方法。

我该怎么做?

最佳答案

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对 header 的属性以在任何对 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。详情将发布在Adopting Modern Objective-C在下一次 Xcode 发布之后(我猜)。

关于objective-c - 是否可以在 Objective-C 中将 -init 方法设为私有(private)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/195078/

相关文章:

objective-c - 更改 NSView 的背景颜色的最佳方法

objective-c - 在 Objective-C 中大写或更改 NSString 的大小写

ios - 自定义 UITableView 标题部分

ios - 在 SwiftUI/Swift/Objective-C/Xamarin 中将底部边框线添

objective-c - Objective-C 中是否存在强类型集合?

objective-c - 在objective-c中@符号代表什么?

ios - 以编程方式调用电话

ios - AppDelegate 的用途是什么,我如何知道何时使用它?

objective-c - Objective-C 中可为空、__nullable 和 _Nulla

ios - UIView 周围的虚线边框