views:

55

answers:

2

Why are class methods such as

+ (NSMutableArray *)array;

needed when there are perfectly fine parent class methods such as

+ arrayWithObjects:(id)firstObj, ...;

which could be set to

[array arrayWithObjects:nil]

and have the same effect.

Are they actually not equivalent things?

+4  A: 

They're convenience methods, to make it easier to just get an autoreleased object fast instead of having to write a lot more to get the same result.

BTW, NSArray does not have an instance method called arrayWithObjects, they are only class methods.

Jacob Relkin
doesn't the "+" indicate that arraryWithObjects is a class method? I don't think I understand why I implied that it is an instance method
Devoted
@Devoted, `[array arrayWithObjects]` is trying to call an instance method that doesn't exist.
Jacob Relkin
You can't call class methods on an instance in Obj-C. The correct call would look like `[NSArray arrayWithObjects:nil];`
kubi
@kubi, exactly what I was saying. `arrayWithObjects` is a class method, not an instance method.
Jacob Relkin
+1  A: 

Jacob's answer is right (so accept that one) but I'll add that the Cocoa framework has a spiffy thing under the hood called class clusters. The idea is that, although you may call [NSArray array], the object you get back is actually a private subclass of NSArray that's optimized for your specific situation. These convenience methods can give the NSArray class a "hint" as to which class to use.

For example, if you call [NSArray array], you get an empty, immutable array. Well, how many different values can an empty immutable array have? Just one. So behind the scenes, Cocoa can return the same empty NSArray to every call to [NSArray array] so that it only ever has to allocate one of these. This is a nifty optimization that saves some memory.

Now, this is really an implementation detail you don't need to concern yourself with, but the takeaway is that you should use the constructor that most closely matches the result you want, especially with collection classes like arrays, sets, and dictionaries, because Apple's implemented a boatload of optimizations that make your application work better.

Alex