Best way of preventing other programmers from calling -init

后端 未结 5 1975
醉梦人生
醉梦人生 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: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….

提交回复
热议问题