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];
An NSData object is simply a container of bytes (raw binary data in the form of 1's and 0's). The primary use for NSData objects is serialization.
An object representing a dynamic byte buffer in memory.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With