Is it okay to call +[NSData dataWithData:] with an NSMutableData object?
Is it a problem for me to do the following to change a mutable data instance immutable?
NSMutableData *mutData = [[NS开发者_开发百科MutableData alloc] init];
//Giving some value to mutData
NSData *immutableData = [NSData dataWithData:mutData];
[mutData release];
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.
No it is not a problem. immutableData
will be initialized with the data in mutData
.
精彩评论