Objective C类初始化
+ (id)packetWithType:(PacketType)packetType
{
return [[[self class] alloc] initWithType:packetType];
}
- (id)initWithType:(PacketType)packetType
{
if ((self = [super init]))
{
// code
}
return self;
}
为什么我们需要第一个类方法,初始化
Why do we need first class method, isn't second one just enough for initialization ??
有方便的构造函数类方法有两个原因。第一个是, [[Thing alloc] initWithFoo:xyz]
的习语真的很常见,但不方便需要在任何地方打字。因此, [Thing thingWithFoo:xzy]
是一个常见的缩写。
There are two reasons for having convenience constructor class methods. The first one is, that the idiom of [[Thing alloc] initWithFoo: xyz]
is really common but inconvenient to have to type anywhere. So, [Thing thingWithFoo: xzy]
is a common abbreviation.
更深层的原因与引用计数。以 init
开头的方法应该返回实例的引用,其所有权将传递给调用者。 Wheras的方便类方法通常返回 autorelease
d引用:
A deeper reason has to do with reference counting. Methods starting with init
are supposed to return a reference of the instance, ownership of which is transferred to the caller. Wheras the convenience class methods usually return autorelease
d references:
+ (id)packetWithType:(PacketType)packetType
{
return [[[[self class] alloc] initWithType:packetType] autorelease];
}
这很重要,为了避免悬挂引用和/ :
This is important to know in order to avoid dangling references and/or memory leaks:
Thing* thing = [[Thing alloc] initWithFoo: xyz];
// Now, *I* own the reference and *I* am responsible for releasing
// it, when I no longer need it.
[thing release]
另一方面,
Thing* thing = [Thing thingWithFoo: xyz];
由nearest NSAutoreleasePool
。调用者不负责释放它(事实上,这将是错误!)。如果要保留引用,则调用者必须实际上保留
:
is owned by the "nearest" NSAutoreleasePool
. The caller is not responsible for releasing it (in fact, that would be wrong!). If the reference is to be kept around, the caller must actually retain
it here:
self->myMember = [thing retain];
您应该知道这些约定,即使使用ARC,因为基本规则仍然有效,甚至如果(在ARC下)它是编译器,谁生成代码来服从他们。 NARC
缩写是一个很好的方式记住,哪个方法名前缀有一定的责任。 此答案有详细信息。
You should know about these conventions even when using ARC, as the underlying rules are still in effect, even if (under ARC) it's the compiler, who generates the code to obey them. The NARC
acronym is a nice way to remember, which method name prefixes come with certain responsibilities. This answer has the details.