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?
Yes, your implementation looks correct. Because
-[NSObject autorelease]returnsself, you can write the return statement asreturn [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:Of course, if
-[NSFoo initWithBar:]exists, you would probably write this method as