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

前端 未结 3 936
梦如初夏
梦如初夏 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:13

    Generally, within a class method, you do use [[self alloc] init]. For example, the canonical way to write a convenience method for a class is:

    + (id)fooWithBar:(Bar *)aBar
    {
        return [[[self alloc] initWithBar:aBar] autorelease];
    }
    

    (Note that in a class method, self refers to the class object.)

    However, you would use [[Foo alloc] init] (that is, an explicit class name) if you actually want an instance of the Foo class (and not a subclass).

提交回复
热议问题