I asked a dumb question the other day (dumb question) about the difference between:
// line1
NSMutableData* myData = [NSMutableData data];
// line2
NSMutableData* myData = [[NSMutableData alloc] init];
It was a dumb question and I didn’t catch my mistake in time. What I meant to ask is, what is the difference between:
// line1 -- added retain
NSMutableData* myData = [[NSMutableData data] retain]; // added retain
// line2
NSMutableData* myData = [[NSMutableData alloc] init];
This could easily still be a dumb question… apologies if that is the case! Is there a real difference? With ARC? I have seen NSXMLParser examples use both methods (some of the Apple examples use [[[NSMutableData alloc] init] autorelease]) and I’m not clear if there is really a difference?
retaincannot be called in ARC compiled code.To answer you’re question though, in a non-ARC environment these are virtually the same.
[NSMutableData data]returns an autoreleased object, by callingretainon it you are taking ownership and are responsible for releasing it at some point.[[NSMutableData alloc] init]returns an object whose retain count is equal to 1 and therefore you are the owner and responsible for releasing it when you are finished with it.Once again though,
retaincannot be used in ARC compiled code, soNSMutableData* myData = [[NSMutableData data] retain];will not compile.And to further clarify, if you are using ARC, you can use either of the following lines and be safe, you do not need to worry about how the object is retained or released.
Edit
Also,
[[[NSMutableData data] retain] autorelease]this code is rather pointless and excessive. What it says is “Give me an auto-released NSMutableData object using the class methoddata, retain this auto-released object for me, and add this object I now own back to the auto-release pool.” So essentially[NSMutableData data]achieves the same result in less code and less overhead. If you really have seen a line like this in Apple’s examples I would be surprised.