cocoainitializationclass-methodinstance-methodsnsmutabledata

What is the difference between the NSMutableData methods "initWith" and "dataWith"?


I'm unclear on the difference between these NSMutableData 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


Solution

  • The class method creates and autoreleases an NSMutableData object.

    The instance method initialzes an object that you have to allocate yourself. The code you've written won't actually do anything, because myMutableDataInstance is nil.

    The class method is roughly equivalent to this:

    NSMutableData * myMutableDataInstance = [NSMutableData alloc];
    [myMutableDataInstance initWithCapacity:WholeLottaData];
    [myMutableDataInstance autorelease];
    

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

    NSMutableData * myMutableDataInstance = [[[NSMutableData alloc]
                                               initWithCapacity:WholeLottaData]
                                               autorelease];
    

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