为什么使用[ClassName alloc]而不是[[self class] alloc]? [英] Why use [ClassName alloc] instead of [[self class] alloc]?
问题描述
我正在阅读Mark Dalrymple的在Mac上学习Objective-C (仅在协议一章中,所以还是相对较新),并试图找出一些答案:
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:
为什么要用自己的名字引用一个类?如果我有一个名为 Foo
的类,为什么我要写
Why would you ever reference a class by its own name? If I had a class called Foo
, why would I ever want to write, say,
[[Foo alloc] init]
而不是
[[[self class] alloc] init]
如果我有Bar的子类,第一个选择不会使我无法写作
If I had a subclass Bar, wouldn't the first option invalidate me from writing
[[Bar alloc] init]
而第二种选择允许吗?第一种选择何时会更好?
whereas the second option would allow it? When would the first option be better?
推荐答案
通常,在类方法中,您确实使用 [ [self alloc] init]
。例如,为类编写便捷方法的规范方法是:
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];
}
(请注意,在类方法中, self
引用类对象。)
(Note that in a class method, self
refers to the class object.)
但是,您将使用 [[Foo alloc] init]
(即显式类名),如果您实际上想要 Foo
类的实例(而不是子类)。
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).
这篇关于为什么使用[ClassName alloc]而不是[[self class] alloc]?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!