tags:

views:

74

answers:

2

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 *) 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  A: 

Yes. It looks right. And your implementation seems like a common practice.

Mykola Golubyev
+2  A: 

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:

+ (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 *) fooWithBar:(NSString *)theBar {
  NSFoo *foo = [[[NSFoo alloc] initWithBar:theBar] autorelease];

  return foo;  
}
Barry Wark
One note: It's somewhat common practice to declare convenience constructors like this as returning id and very common have them do [[self alloc] init] so the method will work with subclasses.
Chuck