Is it okay to call +[NSData dataWithData:] with an NSMutableData object?

Jackless picture Jackless · Jul 26, 2011 · Viewed 9.9k times · Source

Is it a problem for me to do the following to change a mutable data instance immutable?

NSMutableData *mutData = [[NSMutableData alloc] init];
//Giving some value to mutData
NSData *immutableData = [NSData dataWithData:mutData];
[mutData release];

Answer

jscs picture jscs · Jul 27, 2011

This is completely okay, and is in fact one of the primary uses of dataWithData: -- to create an immutable copy of a mutable object.*

NSData also conforms to the NSCopying protocol,** which means you could instead use [mutData copy]. The difference is that dataWithData: returns an object you do not own (it is autoreleased), whereas per memory management rules, copy creates an object for whose memory you are responsible. dataWithData: is equivalent in effect to [[mutData copy] autorelease].

So you can choose either dataWithData: or copy, dependent upon your requirements for the lifetime of the resulting object.


*This also applies to similar methods in other classes which have a mutable subclass, e.g., +[NSArray arrayWithArray:].

**See also "Object Copying" in the Core Competencies Guide.