Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 = [[NSMutableData alloc] init];
//Giving some value to mutData
NSData *immutableData = [NSData dataWithData:mutData];
[mutData release];
like image 694
Jackless Avatar asked Jul 26 '11 20:07

Jackless


People also ask

What is NSData object?

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.

What is Nsmutabledata?

An object representing a dynamic byte buffer in memory.


1 Answers

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.

like image 133
jscs Avatar answered Sep 28 '22 08:09

jscs