OC / Swift / Xcode - 怎么私有化init 方法(禁止调用init方法生成对象)

Is it possible to make the -init method private in Objective-C?

在swift中可以使用 @available

修饰符介绍:官方英文中文
参数是有多种选择的,这里随便写了个示例
如:

class Student: NSObject {
    @objc var name: String
    
    init(name: String) {
        self.name = name
    }
    
    @available(*, unavailable, renamed: "init(name:)")
    override init() {
        self.name = "name"
    }
}

编译报错:

OC推荐使用方式:

方式1: NS_UNAVAILABLE

  - (instancetype)init NS_UNAVAILABLE;

This is a the short version of the unavailable attribute. It first appeared in macOS 10.7 and iOS 5. It is defined in NSObjCRuntime.h as #define NS_UNAVAILABLE UNAVAILABLE_ATTRIBUTE.

There is a version that disables the method only for Swift clients, not for ObjC code:

- (instancetype)init NS_SWIFT_UNAVAILABLE;

方式2: unavailable (编译时就有报错提示)

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;  

在这里插入图片描述

其他方式:

方式3: doesNotRecognizeSelector:

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;
}

方式4:NSAssert

Use NSAssert to throw NSInternalInconsistencyException and show a message:

- (instancetype) init {
    [self release];
    NSAssert(false,@"unavailable, use initWithBlah: instead");
    return nil;
}

方式5:raise:format:

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.

方式6: objc_designated_initializer

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).

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值