Why use [ClassName alloc] instead of [[self class] alloc]?

前端 未结 3 937
梦如初夏
梦如初夏 2021-02-07 05:28

I\'m reading through Mark Dalrymple\'s Learn Objective-C on the Mac (only at the chapter on Protocols, so still relatively newbish) and trying to figure something out:<

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-07 06:15

    You refer to a class by it's name whenever you want exactly that class. If a subclass was derived from that class, a self in the same method would represent that derived class instead. Hence, if you want to explicitly instantiate a superclass, this could be done.

    There are occasions where this might make sense. Either to force the subclass to override the method in order to return an instance of it's class. Or to return a different class, like a placeholder object used in the creation of an NSArray etc.

提交回复
热议问题