views:

178

answers:

1

One thing I'm a bit unclear on is the difference between these NSMutableArray Methods:

// Class Method Style

NSMutableData *myMutableDataInstance = [NSMutableData dataWithLength:WholeLottaData];

and

// Instance Method Style

NSMutableData *myMutableDataInstance = nil;

myMutableDataInstance = [[[NSMutableData alloc] initWithLength:WholeLottaData]] autorelease];

Under the hood, what eactly is the class method doing here? How does it differ from the instance method?

Cheers, Doug

+4  A: 

The class method creates and autoreleases an NSMutableArray object.

The instance method initialzes an object that you have to allocate yourself. The code you've written won't actually do anything, because myMutableArrayInstance is nil. The class method is roughly equivalent to this:

NSMutableArray *myMutableArrayInstance = [NSMutableArray alloc];
[myMutableArrayInstance initWithCapacity:WholeLottaData];
[myMutableArrayInstance autorelease];

And as Peter Hosey notes in comments, it really means this:

NSMutableArray *myMutableArrayInstance = [[[NSMutableArray alloc]
                                           initWithCapacity:WholeLottaData]
                                           autorelease];

which will have different results from the above if the initWithCapacity: method returns a different object.

Kristopher Johnson
Or, more correctly, `[[[NSMutableArray alloc] initWithCapacity:WholeLottaData] autorelease]`. Remember that `init` methods can return a different instance, or release the receiver and return `nil` (after which point you are messaging a deallocated object).
Peter Hosey
Yes. Typing questions at 7am is a rather bug prone ;-). I edited the question. I see, so both flavors do an alloc, which is what I was really wondering about. In general, can I assume all class methods of this type - basically collections and NSMutableData - return an autoreleased object? Thanks, Kristopher.
dugla
Yes, class methods that return new instances will return autoreleased objects.
Sixten Otto