Cocoa-Touch. What Exactly is the Difference Between These NSMutableData Methods?
-
05-07-2019 - |
Question
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
Solution
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.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow