Best way of preventing other programmers from calling -init

后端 未结 5 1942
醉梦人生
醉梦人生 2020-12-23 11:43

When designing a class hierarchy, sometimes the subclass has added a new initWithSomeNewParam method, and it would be desirable to disable calls to the old

相关标签:
5条回答
  • 2020-12-23 12:11

    The syntax has been shortened to just:

    - (instancetype)init NS_UNAVAILABLE;
    
    0 讨论(0)
  • 2020-12-23 12:18

    initWith:Stuff and:OtherStuff should never be more than convenience constructors.

    In that they effectively should call

    self = [self init];
    
    if(self)
    {
        self.stuff = Stuff;
        self.other = OtherStuff;
    }
    

    so [object init] will always return an object in a predefined state, and [object initWithStuff:stuff] will return the object in the predefined state with stuff overridden.

    Basically what I'm getting at is, its bad practice to discourage [object init] especially when someone subclasses your subclass in the future….

    0 讨论(0)
  • 2020-12-23 12:19

    Flag it deprecated? Developers will be developers, you can't stop us all! ;-)

    How do I flag a method as deprecated in Objective-C 2.0?

    0 讨论(0)
  • 2020-12-23 12:21

    To add to what @DarkDust posted, you could alternatively use UNAVAILABLE_ATTRIBUTE

    - (id)init UNAVAILABLE_ATTRIBUTE;
    

    This will throw an error when a user tries to call init on an instance of this class.

    0 讨论(0)
  • 2020-12-23 12:22

    You can explicitly mark your init as being unavailable in your header file:

    - (id) init __unavailable;
    

    or:

    - (id) init __attribute__((unavailable));
    

    With the later syntax, you can even give a reason:

    - (id) init __attribute__((unavailable("Must use initWithFoo: instead.")));
    

    The compiler then issues an error (not a warning) if someone tries to call it.

    0 讨论(0)
提交回复
热议问题