I have a class NSFoo that has a bar property. I want to have a class method to get an instance of NSFoo with the bar property set. This would be similar to the NSString stringWithFormat class method. So the signature would be:
我有一个有酒吧属性的NSFoo类。我想要一个类方法来获取一个带有bar属性集的NSFoo实例。这与NSString stringWithFormat类方法类似。签名将是:
+ (NSFoo *) fooWithBar:(NSString *)theBar;
So I would call it like this:
所以我会这样称呼它:
NSFoo *foo = [NSFoo fooWithBar: @"bar"];
I'm thinking this might be correct:
我认为这可能是正确的:
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[NSFoo alloc] init];
foo.bar = theBar;
[foo autorelease];
return foo;
}
Does that look right?
那看起来不错吗?
2 个解决方案
#1
Yes, your implementation looks correct. Because -[NSObject autorelease]
returns self
, you can write the return statement as return [foo autorelease]
. Some folks recommend autoreleasing an object at allocation if you're going to use autorelease (as opposed to release) since it makes the intention clear and keeps all the memory management code in one place. Your method could then be written as:
是的,您的实施看起来正确。因为 - [NSObject autorelease]返回self,你可以将return语句写为return [foo autorelease]。有些人建议在分配时自动释放一个对象,如果你打算使用自动释放(而不是发布),因为它可以清除意图并将所有内存管理代码保存在一个地方。您的方法可以写成:
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[[NSFoo alloc] init] autorelease];
foo.bar = theBar;
return foo;
}
Of course, if -[NSFoo initWithBar:]
exists, you would probably write this method as
当然,如果 - [NSFoo initWithBar:]存在,您可能会将此方法编写为
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[[NSFoo alloc] initWithBar:theBar] autorelease];
return foo;
}
#2
Yes. It looks right. And your implementation seems like a common practice.
是。看起来不错。你的实现似乎是一种常见的做法。
#1
Yes, your implementation looks correct. Because -[NSObject autorelease]
returns self
, you can write the return statement as return [foo autorelease]
. Some folks recommend autoreleasing an object at allocation if you're going to use autorelease (as opposed to release) since it makes the intention clear and keeps all the memory management code in one place. Your method could then be written as:
是的,您的实施看起来正确。因为 - [NSObject autorelease]返回self,你可以将return语句写为return [foo autorelease]。有些人建议在分配时自动释放一个对象,如果你打算使用自动释放(而不是发布),因为它可以清除意图并将所有内存管理代码保存在一个地方。您的方法可以写成:
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[[NSFoo alloc] init] autorelease];
foo.bar = theBar;
return foo;
}
Of course, if -[NSFoo initWithBar:]
exists, you would probably write this method as
当然,如果 - [NSFoo initWithBar:]存在,您可能会将此方法编写为
+ (NSFoo *) fooWithBar:(NSString *)theBar {
NSFoo *foo = [[[NSFoo alloc] initWithBar:theBar] autorelease];
return foo;
}
#2
Yes. It looks right. And your implementation seems like a common practice.
是。看起来不错。你的实现似乎是一种常见的做法。