PATH  Documentation > Mac OS X > Foundation Reference: Objective-C



Table of Contents

NSData


Inherits from:
NSObject
Conforms to:
NSCoding
NSCopying
NSMutableCopying
NSObject (NSObject)
Declared in:
Foundation/NSData.h
Foundation/NSSerialization.h



Class at a Glance


An NSData object stores immutable data in the form of bytes.

Principal Attributes


Creation



+ data Returns an empty data object.
+ dataWithBytes:length: Returns a data object that contains a copy of the specified bytes.
+ dataWithBytesNoCopy:length: Returns a data object that contains the specified bytes (without copying them).
+ dataWithContentsOfFile: Returns a data object initialized with the contents of a file.
+ dataWithContentsOfMappedFile: Returns a data object initialized with the contents of a mapped file.
+ dataWithData: Returns a data object initialized with the contents of another data object.

Commonly Used Methods



- bytes Returns a pointer to the data object's contents.
- getBytes: Copies the data object's contents into a buffer.
- length Returns the number of bytes contained by the data object.

Primitive Methods



- bytes Returns a pointer to the data object's contents.
- length Returns the number of bytes contained by the data object.




Class Description


NSData and its subclass NSMutableData provide data objects, object-oriented wrappers for byte buffers. Data objects let simple allocated buffers (that is, data with no embedded pointers) take on the behavior of Foundation Kit objects. NSData creates static data objects, and NSMutableData creates dynamic data objects. They're typically used for data storage, and are also useful in Distributed Objects applications, where data contained in data objects can be copied or moved between applications.

Data objects can wrap data of any size. When the data size is more than a few memory pages, the object uses virtual memory management. A data object can also wrap pre-existing data, regardless of how the data was allocated. The object contains no information about the data itself (such as its type); the responsibility for deciding how to use the data lies with the client. In particular, it will not handle byte-order swapping when distributed between big-endian and little-endian machines. For typed data, use NSValue.

Data objects provide an operating system-independent way to benefit from copy-on-write memory. The copy-on-write technique means that when data is copied through a virtual memory copy, an actual copy of the data is not made until there is an attempt to modify it.

Because of the nature of class clusters, data objects are not actual instances of the NSData or NSMutableData classes but instead are instances of one of their private subclasses. Although a data object's class is private, its interface is public, as declared by these abstract superclasses, NSData and NSMutableData.

Generally, you instantiate a data object by sending one of the data... messages to either the NSData or NSMutableData class object. These methods return a data object containing the bytes you pass in as arguments. If you use one of the data... methods whose name does not include NoCopy (such as dataWithBytes:length:), the bytes to be contained by the data object are copied as part of the instantiation process, and the data object then contains the copied bytes. When you subsequently release a data object that has been instantiated in this manner, the bytes contained by the data object-those that were copied during instantiation-are automatically freed. If you instantiate a data object with one of the methods whose name includes NoCopy, however, (such as dataWithBytesNoCopy:length:) the bytes are not copied and are freed when the data object is released.

NSData and NSMutableData adopt the NSCopying and NSMutableCopying protocols, making it convenient to convert between efficient, read-only data objects and mutable data objects.

NSData's two primitive methods- bytes and length-provide the basis for all of the other methods in the interface. The bytes method returns a pointer to the bytes contained in the data object. length returns the number of bytes contained in the data object.

NSData provides access methods for copying bytes from a data object into a specified buffer. getBytes: copies all of the bytes into a buffer, whereas getBytes:length: copies bytes into a buffer of a given length. getBytes:range: copies a range of bytes from a starting point within the bytes themselves. To extract a data object that contains a subset of the bytes in another data object, use the subdataWithRange: method. Or, you can use the description method to return an NSString representation of the bytes in a data object.

To determine if two data objects are equal, use the isEqualToData: method, which does a byte-for-byte comparison.

The writeToFile:atomically: method lets you write the contents of a data object to a local file. The writeToURL:atomically: method lets you write the contents of a data object to a location on the Internet.




Adopted Protocols


NSCoding
- encodeWithCoder:
- initWithCoder:
NSCopying
- copyWithZone:
NSMutableCopying
- mutableCopyWithZone:


Method Types


Creating data objects
+ data
+ dataWithBytes:length:
+ dataWithBytesNoCopy:length:
+ dataWithContentsOfFile:
+ dataWithContentsOfMappedFile:
+ dataWithContentsOfURL:
+ dataWithData:
- initWithBytes:length:
- initWithBytesNoCopy:length:
- initWithContentsOfFile:
- initWithContentsOfMappedFile:
- initWithContentsOfURL:
- initWithData:
Accessing data
- bytes
- description
- getBytes:
- getBytes:length:
- getBytes:range:
- subdataWithRange:
Deserializing data
- deserializeAlignedBytesLengthAtCursor:
- deserializeBytes:length:atCursor:
- deserializeDataAt:ofObjCType:atCursor:context:
- deserializeIntAtCursor:
- deserializeIntAtIndex:
- deserializeInts:count:atCursor:
- deserializeInts:count:atIndex:
Testing data
- isEqualToData:
- length
Storing data
- writeToFile:atomically:
- writeToURL:atomically:


Constructors






Class Methods



data

+ (id)data

Creates and returns an empty data object. This method is declared primarily for the use of mutable subclasses of NSData.



dataWithBytes:length:

+ (id)dataWithBytes:(const void *)bytes length:(unsigned)length

Creates and returns a data object containing length bytes copied from the buffer bytes.

See Also: + dataWithBytesNoCopy:length:



dataWithBytesNoCopy:length:

+ (id)dataWithBytesNoCopy:(void *)bytes length:(unsigned)length

Creates and returns a data object that holds length bytes from the buffer bytes.

See Also: + dataWithBytes:length:



dataWithContentsOfFile:

+ (id)dataWithContentsOfFile:(NSString *)path

Creates and returns a data object by reading every byte from the file specified by path.

The following code example creates a data object myData initialized with the contents of myFile.txt. The path must be absolute.

NSString *thePath = @"/u/smith/myFile.txt";
NSData *myData = [NSData dataWithContentsOfFile:thePath];

See Also: + dataWithContentsOfMappedFile:



dataWithContentsOfMappedFile:

+ (id)dataWithContentsOfMappedFile:(NSString *)path

Creates and returns a data object from the mapped file specified by path. Because of file mapping restrictions, this method should only be used if the file is guaranteed to exist for the duration of the data object's existence. It is generally safer to use the dataWithContentsOfFile: method.

This methods assumes mapped files are available from the underlying operating system. A mapped file uses virtual memory techniques to avoid copying pages of the file into memory until they are actually needed.

See Also: + dataWithContentsOfFile:



dataWithContentsOfURL:

+ (id)dataWithContentsOfURL:(NSURL *)anURL

Description forthcoming.

dataWithData:

+ (id)dataWithData:(NSData *)aData

Creates and returns a data object containing the contents of another data object, aData.




Instance Methods



bytes

- (const void *)bytes

Returns a pointer to the data object's contents. This method returns read-only access to the data.

See Also: - description, - getBytes:, - getBytes:length:, - getBytes:range:



description

- (NSString *)description

Returns an NSString object that contains a hexadecimal representation of the receiver's contents in the property list format for NSData objects.

See Also: - bytes, - getBytes:, - getBytes:length:, - getBytes:range:



deserializeAlignedBytesLengthAtCursor:

- (unsigned int)deserializeAlignedBytesLengthAtCursor:(unsigned *)cursor

Reads a sequence of bytes from the receiver beginning at location cursor and returns them formatted as an unsigned integer. On return, cursor is set to the location just past the bytes that were read.

Use this method to read an integer that was serialized using the serializeAlignedBytesLength: method of NSMutableData. This method ignores any filler bytes that were serialized by the serializeAlignedBytesLength: method.

See Also: - deserializeIntAtCursor:, - deserializeIntAtIndex:



deserializeBytes:length:atCursor:

- (void)deserializeBytes:(void *)buffer length:(unsigned)bytes atCursor:(unsigned *)cursor

Reads a sequence of bytes from the receiver beginning at location cursor and places them in buffer. The bytes parameter specifies the number of bytes to be read. On return, cursor is set to the location just beyond the bytes that were read.

See Also: - getBytes:range:



deserializeDataAt:ofObjCType:atCursor:context:

- (void)deserializeDataAt:(void *)data ofObjCType:(const char *)type atCursor:(unsigned *)cursor context:(id <NSObjCTypeSerializationCallBack>)callback

Reads a sequence of bytes from the receiver beginning at location cursor and places them in data. The bytes are formatted according to the Objective-C type code given in type. If type specifies an object, callback is used to deserialize the object; in such a case, callback must itself be an object that conforms to the NSObjCTypeSerializationCallBack protocol. If type does not specify an object, callback can be nil.

For information on creating an Objective-C type code suitable for type, see the description of the @encode() compiler directive in Object-Oriented Programming and the Objective-C Language.



deserializeIntAtCursor:

- (int)deserializeIntAtCursor:(unsigned *)cursor

Reads a sequence of bytes from the receiver beginning at location cursor and returns them as an integer value. On return, cursor is set to the location just past the bytes that were read.

See Also: - deserializeIntAtIndex:, - serializeInt: (NSMutableData)



deserializeIntAtIndex:

- (int)deserializeIntAtIndex:(unsigned)index

Reads a sequence of bytes from the receiver starting at index and returns them as an integer value.

See Also: - getBytes:range:, - serializeInt: (NSMutableData)



deserializeInts:count:atCursor:

- (void)deserializeInts:(int *)intBuffer count:(unsigned)numInts atCursor:(unsigned *)cursor

Reads numInts integers as a sequence of bytes from the receiver and copies them into intBuffer. The bytes are read from the receiver beginning at location cursor. On return, cursor is set to the location just past the integers that were read.

See Also: - getBytes:range:, - deserializeIntAtCursor:, - serializeInt: (NSMutableData)



deserializeInts:count:atIndex:

- (void)deserializeInts:(int *)intBuffer count:(unsigned)numInts atIndex:(unsigned)index

Reads numInts integers as a sequence of bytes from the receiver and copies them into intBuffer. The bytes are read from the receiver starting at index.

See Also: - getBytes:range:, - deserializeIntAtIndex:, - serializeInt: (NSMutableData)



getBytes:

- (void)getBytes:(void *)buffer

Copies a data object's contents into buffer.

For example, the following code excerpt initializes a data object myData with the NSString myString. It then uses getBytes: to copy the contents of myData into aBuffer.

unsigned char aBuffer[20];
NSString *myString = @"Test string.";
NSData *myData = [NSData dataWithBytes:[myString cString]
        length:[myString cStringLength]];
	
[myData getBytes:aBuffer];

See Also: - bytes, - description, - getBytes:length:, - getBytes:range:



getBytes:length:

- (void)getBytes:(void *)buffer length:(unsigned)length

Copies up to length bytes from the start of the receiver into buffer.

See Also: - bytes, - description, - getBytes:, - getBytes:range:



getBytes:range:

- (void)getBytes:(void *)buffer range:(NSRange)range

Copies the receiver's contents into buffer, from range that is within the bytes in the object. If range isn't within the receiver's range of bytes, an NSRangeException is raised.

See Also: - bytes, - description, - getBytes:, - getBytes:length:



initWithBytes:length:

- (id)initWithBytes:(const void *)bytes length:(unsigned)length

Initializes a newly allocated data object by adding to it length bytes of data copied from the buffer bytes. Returns self.

See Also: + dataWithBytes:length:, - initWithBytesNoCopy:length:



initWithBytesNoCopy:length:

- (id)initWithBytesNoCopy:(void *)bytes length:(unsigned)length

Initializes a newly allocated data object by adding to it length bytes of data from the buffer bytes. Returns self.

See Also: + dataWithBytes:length:, - initWithBytes:length:



initWithContentsOfFile:

- (id)initWithContentsOfFile:(NSString *)path

Initializes a newly allocated data object by reading into it the data from the file specified by path. Returns self.

See Also: + dataWithContentsOfFile:, - initWithContentsOfMappedFile:



initWithContentsOfMappedFile:

- (id)initWithContentsOfMappedFile:(NSString *)path

Initializes a newly allocated data object by reading into it the mapped file specified by path. Returns self.

See Also: + dataWithContentsOfMappedFile:, - initWithContentsOfFile:



initWithContentsOfURL:

- (id)initWithContentsOfURL:(NSURL *)anURL

Description forthcoming.

initWithData:

- (id)initWithData:(NSData *)data

Initializes a newly allocated data object by placing in it the contents of another data object, data. Returns self.



isEqualToData:

- (BOOL)isEqualToData:(NSData *)otherData

Compares the receiving data object to otherData. If the contents of otherData are equal to the contents of the receiver, this method returns YES. If not, it returns NO. Two data objects are equal if they hold the same number of bytes, and if the bytes at the same position in the objects are the same.



length

- (unsigned)length

Returns the number of bytes contained in the receiver.



subdataWithRange:

- (NSData *)subdataWithRange:(NSRange)range

Returns a data object containing a copy of the receiver's bytes that fall within the limits specified by range. If range isn't within the receiver's range of bytes, an NSRangeException is raised.

For example, the following code excerpt initializes a data object, data2, to contain a sub-range of data1:

String myString = "ABCDEFG";
range = new NSRange(2,4);
NSData data1 = new NSData(myString.getBytes());
NSData data2 = data1.subdataWithRange(range);

NSString *myString = @"ABCDEFG"; NSRange range = {2, 4}; NSData *data1, *data2;       data1 = [NSData dataWithBytes:[myString cString]         length:[myString cStringLength]];      data2 = [data1 subdataWithRange:range];

The result of this excerpt is that data2 contains "CDEF".



writeToFile:atomically:

- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)flag

Writes the bytes in the receiver to the file specified by path. If flag is YES, the data is written to a backup file and then, assuming no errors occur, the backup file is renamed to the specified file name. Otherwise, the data is written directly to the specified file.

If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

This method returns YES if the operation succeeds; otherwise, it returns NO.



writeToURL:atomically:

- (BOOL)writeToURL:(NSURL)anURL atomically:(BOOL)atomically

Writes the bytes in the receiver to the location specified by anURL. If atomically is YES, the data is written to a backup file and then, assuming no errors occur, the backup file is renamed to the specified name. Otherwise, the data is written directly to the specified location. atomically is ignored if the anURL is not of a type the supports atomic writes

This method returns YES if the operation succeeds; otherwise, it returns NO.




Table of Contents