iOS Developer Library — Pre-Release

Developer

Foundation Framework Reference NSData Class Reference

Options
Deployment Target:

On This Page
Language:

NSData

NSData and its mutable 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 objects.

NSData creates static data objects, and NSMutableData creates dynamic data objects. NSData and NSMutableData are 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.

The size of the data is subject to a theoretical limit of about 8 ExaBytes (in practice, the limit should not be a factor).

NSData is “toll-free bridged” with its Core Foundation counterpart, CFDataRef. See Toll-Free Bridging for more information on toll-free bridging.

Saving Data

The NSData class and its subclasses provide methods to quickly and easily save their contents to disk. To minimize the risk of data loss, these methods provide the option of saving the data atomically. Atomic writes guarantee that the data is either saved in its entirety, or it fails completely. The atomic write begins by writing the data to a temporary file. If this write succeeds, then the method moves the temporary file to its final location.

While atomic write operations minimize the risk of data loss due to corrupt or partially-written files, they may not be appropriate when writing to a temporary directory, the user’s home directory or other publicly accessible directories. Any time you work with a publicly accessible file, you should treat that file as an untrusted and potentially dangerous resource. An attacker may compromise or corrupt these files. The attacker can also replace the files with hard or symbolic links, causing your write operations to overwrite or corrupt other system resources.

Avoid using the writeToURL:atomically: method (and the related methods) when working inside a publicly accessible directory. Instead initialize an NSFileHandle object with an existing file descriptor and use the NSFileHandle methods to securely write the file.

For more information, see Securing File Operations in Secure Coding Guide.

Inheritance


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in iOS 2.0 and later.
  • Creates and returns an empty data object.

    Declaration

    Objective-C

    + (instancetype)data

    Return Value

    An empty data object.

    Discussion

    This method is declared primarily for the use of mutable subclasses of NSData.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

  • Creates and returns a data object containing a given number of bytes copied from a given buffer.

    Declaration

    Objective-C

    + (instancetype)dataWithBytes:(const void *)bytes length:(NSUInteger)length

    Parameters

    bytes

    A buffer containing data for the new object.

    length

    The number of bytes to copy from bytes. This value must not exceed the length of bytes.

    Return Value

    A data object containing length bytes copied from the buffer bytes. Returns nil if the data object could not be created.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Objective-C

    + (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length

    Parameters

    bytes

    A buffer containing data for the new object. bytes must point to a memory block allocated with malloc.

    length

    The number of bytes to hold from bytes. This value must not exceed the length of bytes.

    Return Value

    A data object that holds length bytes from the buffer bytes. Returns nil if the data object could not be created.

    Discussion

    The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

  • Creates and returns a data object that holds a given number of bytes from a given buffer.

    Declaration

    Objective-C

    + (instancetype)dataWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)freeWhenDone

    Parameters

    bytes

    A buffer containing data for the new object. If freeWhenDone is YEStrue, bytes must point to a memory block allocated with malloc.

    length

    The number of bytes to hold from bytes. This value must not exceed the length of bytes.

    freeWhenDone

    If YEStrue, the returned object takes ownership of the bytes pointer and frees it on deallocation.

    Return Value

    A data object that holds length bytes from the buffer bytes. Returns nil if the data object could not be created.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Objective-C

    + (instancetype)dataWithContentsOfFile:(NSString *)path

    Parameters

    path

    The absolute path of the file from which to read data.

    Return Value

    A data object by reading every byte from the file specified by path. Returns nil if the data object could not be created.

    Discussion

    This method is equivalent to dataWithContentsOfFile:options:error: with no options. If you need to know what was the reason for failure, use dataWithContentsOfFile:options:error:.

    A sample using this method can be found in Working With Binary Data.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Objective-C

    + (instancetype)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

    Parameters

    path

    The absolute path of the file from which to read data.

    mask

    A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions”.

    errorPtr

    If an error occurs, upon return contains an NSError object that describes the problem.

    Return Value

    A data object by reading every byte from the file specified by path. Returns nil if the data object could not be created.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

  • Creates and returns a data object from the mapped file specified by path.

    Declaration

    Swift

    class func dataWithContentsOfMappedFile(_ path: String) -> AnyObject?

    Objective-C

    + (id)dataWithContentsOfMappedFile:(NSString *)path

    Parameters

    path

    The absolute path of the file from which to read data.

    Return Value

    A data object from the mapped file specified by path. Returns nil if the data object could not be created.

    Discussion

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 8.0.

  • Returns a data object containing the data from the location specified by a given URL.

    Declaration

    Objective-C

    + (instancetype)dataWithContentsOfURL:(NSURL *)aURL

    Parameters

    aURL

    The URL from which to read data.

    Return Value

    A data object containing the data from the location specified by aURL. Returns nil if the data object could not be created.

    Discussion

    This method is ideal for converting data:// URLs to NSData objects, and can also be used for reading short files synchronously. If you need to read potentially large files, use inputStreamWithURL: to open a stream, then read the file a piece at a time.

    If you need to know the reason for failure, use dataWithContentsOfURL:options:error:.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

  • Creates and returns a data object containing the data from the location specified by aURL.

    Declaration

    Objective-C

    + (instancetype)dataWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

    Parameters

    aURL

    The URL from which to read data.

    mask

    A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions”.

    errorPtr

    If there is an error reading in the data, upon return contains an NSError object that describes the problem.

    Discussion

    This method is ideal for converting data:// URLs to NSData objects, and can also be used for reading short files synchronously. If you need to read potentially large files, use inputStreamWithURL: to open a stream, then read the file a piece at a time.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

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

    Declaration

    Objective-C

    + (instancetype)dataWithData:(NSData *)aData

    Parameters

    aData

    A data object.

    Return Value

    A data object containing the contents of aData. Returns nil if the data object could not be created.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized with the given Base-64 encoded data.

    Declaration

    Swift

    init?(base64EncodedData base64Data: NSData, options options: NSDataBase64DecodingOptions)

    Objective-C

    - (instancetype)initWithBase64EncodedData:(NSData *)base64Data options:(NSDataBase64DecodingOptions)options

    Parameters

    base64Data

    A Base-64, UTF-8 encoded data object.

    options

    A mask that specifies options for Base-64 decoding the data. Possible values are given in “NSDataBase64DecodingOptions”.

    Return Value

    A data object containing the Base-64 decoded data. Returns nil if the data object could not be decoded.

    Discussion

    The default implementation of this method will reject non-alphabet characters, including line break characters. To support different encodings and ignore non-alphabet characters, specify an options value of NSDataBase64DecodingIgnoreUnknownCharacters.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later.

  • Returns a data object initialized with the given Base-64 encoded string.

    Declaration

    Swift

    init?(base64EncodedString base64String: String, options options: NSDataBase64DecodingOptions)

    Objective-C

    - (instancetype)initWithBase64EncodedString:(NSString *)base64String options:(NSDataBase64DecodingOptions)options

    Parameters

    base64String

    A Base-64 encoded string.

    options

    A mask that specifies options for Base-64 decoding the data. Possible values are given in “NSDataBase64DecodingOptions”.

    Return Value

    A data object built by Base-64 decoding the provided string. Returns nil if the data object could not be decoded.

    Discussion

    The default implementation of this method will reject non-alphabet characters, including line break characters. To support different encodings and ignore non-alphabet characters, specify an options value of NSDataBase64DecodingIgnoreUnknownCharacters.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later.

  • Returns a data object initialized with the given Base-64 encoded string.

    Deprecation Statement

    You should transition to either initWithBase64EncodedString:options: or initWithBase64EncodedData:options:.

    Declaration

    Objective-C

    - (id)initWithBase64Encoding:(NSString *)base64String

    Parameters

    base64String

    A Base-64 encoded string.

    Return Value

    A data object built by Base-64 decoding the provided string. Returns nil if the data object could not be decoded.

    Special Considerations

    Although this method was only introduced publicly for iOS 7, it has existed since iOS 4; you can use it if your application needs to target an operating system prior to iOS 7. This method behaves like initWithBase64EncodedString:options:, but ignores all unknown characters.

    Import Statement

    Objective-C

    @import Foundation;

    Availability

    Available in iOS 4.0 and later.

    Deprecated in iOS 7.0.

  • Returns a data object initialized by adding to it a given number of bytes of data copied from a given buffer.

    Declaration

    Swift

    init(bytes bytes: UnsafePointer<Void>, length length: Int)

    Objective-C

    - (instancetype)initWithBytes:(const void *)bytes length:(NSUInteger)length

    Discussion

    A data object initialized by adding to it length bytes of data copied from the buffer bytes. The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized by adding to it a given number of bytes of data from a given buffer.

    Declaration

    Swift

    init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length length: Int)

    Objective-C

    - (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length

    Parameters

    bytes

    A buffer containing data for the new object. bytes must point to a memory block allocated with malloc.

    length

    The number of bytes to hold from bytes. This value must not exceed the length of bytes.

    Return Value

    A data object initialized by adding to it length bytes of data from the buffer bytes. The returned object might be different than the original receiver.

    Discussion

    The returned object takes ownership of the bytes pointer and frees it on deallocation. Therefore, bytes must point to a memory block allocated with malloc.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized by adding to it a given number of bytes of data from a given buffer, with a custom deallocator block.

    Declaration

    Swift

    init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length length: Int, deallocator deallocator: ((UnsafeMutablePointer<Void>, Int) -> Void)?)

    Objective-C

    - (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length deallocator:(void (^)(void *bytes, NSUInteger length))deallocator

    Parameters

    bytes

    A buffer containing data for the new object.

    length

    The number of bytes to hold from bytes. This value must not exceed the length of bytes.

    deallocator

    A block to invoke when the resulting NSData object is deallocated.

    Return Value

    A data object initialized by adding to it length bytes of data from the buffer bytes. The returned object might be different than the original receiver.

    Discussion

    Use this method to define your own deallocation behavior for the data buffer you provide.

    In order to avoid any inadvertent strong reference cycles, you should avoid capturing pointers to any objects that may in turn maintain strong references to the NSData object. This includes explicit references to self, and implicit references to self due to direct instance variable access. To make it easier to avoid these references, the deallocator block takes two parameters, a pointer to the buffer, and its length; you should always use these values instead of trying to use references from outside the block.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later.

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

    Declaration

    Swift

    init(bytesNoCopy bytes: UnsafeMutablePointer<Void>, length length: Int, freeWhenDone flag: Bool)

    Objective-C

    - (instancetype)initWithBytesNoCopy:(void *)bytes length:(NSUInteger)length freeWhenDone:(BOOL)flag

    Parameters

    bytes

    A buffer containing data for the new object. If flag is YEStrue, bytes must point to a memory block allocated with malloc.

    length

    The number of bytes to hold from bytes. This value must not exceed the length of bytes.

    flag

    If YEStrue, the returned object takes ownership of the bytes pointer and frees it on deallocation.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized by reading into it the data from the file specified by a given path.

    Declaration

    Swift

    init?(contentsOfFile path: String)

    Objective-C

    - (instancetype)initWithContentsOfFile:(NSString *)path

    Parameters

    path

    The absolute path of the file from which to read data.

    Return Value

    A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver.

    Discussion

    This method is equivalent to initWithContentsOfFile:options:error: with no options.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized by reading into it the data from the file specified by a given path.

    Declaration

    Swift

    init?(contentsOfFile path: String, options mask: NSDataReadingOptions, error errorPtr: NSErrorPointer)

    Objective-C

    - (instancetype)initWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

    Parameters

    path

    The absolute path of the file from which to read data.

    mask

    A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions”.

    errorPtr

    If an error occurs, upon return contains an NSError object that describes the problem.

    Return Value

    A data object initialized by reading into it the data from the file specified by path. The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized by reading into it the mapped file specified by a given path.

    Declaration

    Swift

    init?(contentsOfMappedFile path: String)

    Objective-C

    - (id)initWithContentsOfMappedFile:(NSString *)path

    Parameters

    path

    The absolute path of the file from which to read data.

    Return Value

    A data object initialized by reading into it the mapped file specified by path. The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 8.0.

  • Initializes a newly allocated data object initialized with the data from the location specified by aURL.

    Declaration

    Swift

    init?(contentsOfURL aURL: NSURL)

    Objective-C

    - (instancetype)initWithContentsOfURL:(NSURL *)aURL

    Parameters

    aURL

    The URL from which to read data

    Return Value

    An NSData object initialized with the data from the location specified by aURL. The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized with the data from the location specified by a given URL.

    Declaration

    Swift

    init?(contentsOfURL aURL: NSURL, options mask: NSDataReadingOptions, error errorPtr: NSErrorPointer)

    Objective-C

    - (instancetype)initWithContentsOfURL:(NSURL *)aURL options:(NSDataReadingOptions)mask error:(NSError **)errorPtr

    Parameters

    aURL

    The URL from which to read data.

    mask

    A mask that specifies options for reading the data. Constant components are described in “NSDataReadingOptions”.

    errorPtr

    If there is an error reading in the data, upon return contains an NSError object that describes the problem.

    Return Value

    A data object initialized with the data from the location specified by aURL. The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object initialized with the contents of another data object.

    Declaration

    Swift

    init(data data: NSData)

    Objective-C

    - (instancetype)initWithData:(NSData *)data

    Parameters

    data

    A data object.

    Return Value

    A data object initialized with the contents data. The returned object might be different than the original receiver.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    See Also

    + dataWithData:

  • bytes bytes Property

    A pointer to the receiver’s contents. (read-only)

    Declaration

    Swift

    var bytes: UnsafePointer<Void> { get }

    Objective-C

    @property(readonly) const void *bytes

    Discussion

    If the length of the NSData object is 0, this method returns nil.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • A string that contains a hexadecimal representation of the object’s contents in a property list format. (read-only)

    Declaration

    Swift

    var description: String { get }

    Objective-C

    @property(readonly, copy) NSString *description

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Enumerate through each range of bytes in the data object using a block.

    Declaration

    Swift

    func enumerateByteRangesUsingBlock(_ block: (UnsafePointer<Void>, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void)

    Objective-C

    - (void)enumerateByteRangesUsingBlock:(void (^)(const void *bytes, NSRange byteRange, BOOL *stop))block

    Parameters

    block

    The block to apply to byte ranges in the array.

    The block takes three arguments:

    bytes

    The bytes for the current range.

    byteRange

    The range of the current data bytes.

    stop

    A reference to a Boolean value. The block can set the value to YEStrue to stop further processing of the data. The stop argument is an out-only argument. You should only ever set this Boolean to YEStrue within the Block.

    Discussion

    The enumeration block is called once for each contiguous region of memory in the receiver (once total for a contiguous NSData object), until either all bytes have been enumerated, or the stop parameter is set to YEStrue.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later.

  • Copies a data object’s contents into a given buffer.

    Deprecation Statement

    This method is unsafe because it could potentially cause buffer overruns. You should use getBytes:length: or getBytes:range: instead.

    Declaration

    Swift

    func getBytes(_ buffer: UnsafeMutablePointer<Void>)

    Objective-C

    - (void)getBytes:(void *)buffer

    Parameters

    buffer

    A buffer into which to copy the receiver's data. The buffer must be at least length bytes.

    Discussion

    You can see a sample using this method in Working With Binary Data.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

    Deprecated in iOS 8.0.

  • Copies a number of bytes from the start of the receiver's data into a given buffer.

    Declaration

    Swift

    func getBytes(_ buffer: UnsafeMutablePointer<Void>, length length: Int)

    Objective-C

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

    Parameters

    buffer

    A buffer into which to copy data.

    length

    The number of bytes from the start of the receiver's data to copy to buffer.

    Discussion

    The number of bytes copied is the smaller of the length parameter and the length of the data encapsulated in the object.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Copies a range of bytes from the receiver’s data into a given buffer.

    Declaration

    Swift

    func getBytes(_ buffer: UnsafeMutablePointer<Void>, range range: NSRange)

    Objective-C

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

    Parameters

    buffer

    A buffer into which to copy data.

    range

    The range of bytes in the receiver's data to copy to buffer. The range must lie within the range of bytes of the receiver's data.

    Discussion

    If range isn’t within the receiver’s range of bytes, an NSRangeException is raised.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Returns a data object containing the receiver’s bytes that fall within the limits specified by a given range.

    Declaration

    Swift

    func subdataWithRange(_ range: NSRange) -> NSData

    Objective-C

    - (NSData *)subdataWithRange:(NSRange)range

    Parameters

    range

    The range in the receiver from which to get the data. The range must not exceed the bounds of the receiver.

    Return Value

    A data object containing the receiver’s bytes that fall within the limits specified by range. If range isn’t within the receiver’s range of bytes, raises NSRangeException.

    Discussion

    A sample using this method can be found in Working With Binary Data.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Finds and returns the range of the first occurrence of the given data, within the given range, subject to given options.

    Declaration

    Swift

    func rangeOfData(_ dataToFind: NSData, options mask: NSDataSearchOptions, range searchRange: NSRange) -> NSRange

    Objective-C

    - (NSRange)rangeOfData:(NSData *)dataToFind options:(NSDataSearchOptions)mask range:(NSRange)searchRange

    Parameters

    dataToFind

    The data for which to search. This value must not be nil.

    mask

    A mask specifying search options. The NSDataSearchOptions options may be specified singly or by combining them with the C bitwise OR operator.

    searchRange

    The range within the receiver in which to search for dataToFind. If this range is not within the receiver’s range of bytes, an NSRangeException raised.

    Return Value

    An NSRange structure giving the location and length of dataToFind within searchRange, modulo the options in mask. The range returned is relative to the start of the searched data, not the passed-in search range. Returns {NSNotFound, 0} if dataToFind is not found or is empty (@"").

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Compares the receiving data object to otherData.

    Declaration

    Swift

    func isEqualToData(_ otherData: NSData) -> Bool

    Objective-C

    - (BOOL)isEqualToData:(NSData *)otherData

    Parameters

    otherData

    The data object with which to compare the receiver.

    Return Value

    YEStrue if the contents of otherData are equal to the contents of the receiver, otherwise NOfalse.

    Discussion

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • length length Property

    The number of bytes contained by the data object. (read-only)

    Declaration

    Swift

    var length: Int { get }

    Objective-C

    @property(readonly) NSUInteger length

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Writes the bytes in the receiver to the file specified by a given path.

    Declaration

    Swift

    func writeToFile(_ path: String, atomically atomically: Bool) -> Bool

    Objective-C

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

    Parameters

    path

    The location to which to write the receiver's bytes. If path contains a tilde (~) character, you must expand it with stringByExpandingTildeInPath before invoking this method.

    atomically

    If YEStrue, the data is written to a backup file, and then—assuming no errors occur—the backup file is renamed to the name specified by path; otherwise, the data is written directly to path.

    Return Value

    YEStrue if the operation succeeds, otherwise NOfalse.

    Discussion

    This method may not be appropriate when writing to publicly accessible files. To securely write data to a public location, use NSFileHandle instead. For more information, seeSecuring File Operations in Secure Coding Guide.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Writes the bytes in the receiver to the file specified by a given path.

    Declaration

    Swift

    func writeToFile(_ path: String, options mask: NSDataWritingOptions, error errorPtr: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)writeToFile:(NSString *)path options:(NSDataWritingOptions)mask error:(NSError **)errorPtr

    Parameters

    path

    The location to which to write the receiver's bytes.

    mask

    A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.

    errorPtr

    If there is an error writing out the data, upon return contains an NSError object that describes the problem.

    Return Value

    YEStrue if the operation succeeds, otherwise NOfalse.

    Discussion

    This method may not be appropriate when writing to publicly accessible files. To securely write data to a public location, use NSFileHandle instead. For more information, seeSecuring File Operations in Secure Coding Guide.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Writes the bytes in the receiver to the location specified by aURL.

    Declaration

    Swift

    func writeToURL(_ aURL: NSURL, atomically atomically: Bool) -> Bool

    Objective-C

    - (BOOL)writeToURL:(NSURL *)aURL atomically:(BOOL)atomically

    Parameters

    aURL

    The location to which to write the receiver's bytes. Only file:// URLs are supported.

    atomically

    If YEStrue, the data is written to a backup location, and then—assuming no errors occur—the backup location is renamed to the name specified by aURL; otherwise, the data is written directly to aURL. atomically is ignored if aURL is not of a type the supports atomic writes.

    Return Value

    YEStrue if the operation succeeds, otherwise NOfalse.

    Discussion

    Since at present only file:// URLs are supported, there is no difference between this method and writeToFile:atomically:, except for the type of the first argument.

    This method may not be appropriate when writing to publicly accessible files. To securely write data to a public location, use NSFileHandle instead. For more information, seeSecuring File Operations in Secure Coding Guide.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Writes the bytes in the receiver to the location specified by a given URL.

    Declaration

    Swift

    func writeToURL(_ aURL: NSURL, options mask: NSDataWritingOptions, error errorPtr: NSErrorPointer) -> Bool

    Objective-C

    - (BOOL)writeToURL:(NSURL *)aURL options:(NSDataWritingOptions)mask error:(NSError **)errorPtr

    Parameters

    aURL

    The location to which to write the receiver's bytes.

    mask

    A mask that specifies options for writing the data. Constant components are described in “NSDataWritingOptions”.

    errorPtr

    If there is an error writing out the data, upon return contains an NSError object that describes the problem.

    Return Value

    YEStrue if the operation succeeds, otherwise NOfalse.

    Discussion

    Since at present only file:// URLs are supported, there is no difference between this method and writeToFile:options:error:, except for the type of the first argument.

    This method may not be appropriate when writing to publicly accessible files. To securely write data to a public location, use NSFileHandle instead. For more information, seeSecuring File Operations in Secure Coding Guide.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 2.0 and later.

  • Options for methods used to read NSData objects.

    Declaration

    Swift

    struct NSDataReadingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var DataReadingMappedIfSafe: NSDataReadingOptions { get } static var DataReadingUncached: NSDataReadingOptions { get } static var DataReadingMappedAlways: NSDataReadingOptions { get } static var DataReadingMapped: NSDataReadingOptions { get } static var MappedRead: NSDataReadingOptions { get } static var UncachedRead: NSDataReadingOptions { get } }

    Objective-C

    enum { NSDataReadingMappedIfSafe = 1UL << 0, NSDataReadingUncached = 1UL << 1, NSDataReadingMappedAlways = 1UL << 3, }; typedef NSUInteger NSDataReadingOptions;

    Constants

    • DataReadingMappedIfSafe

      NSDataReadingMappedIfSafe

      A hint indicating the file should be mapped into virtual memory, if possible and safe.

      Available in iOS 5.0 and later.

    • DataReadingUncached

      NSDataReadingUncached

      A hint indicating the file should not be stored in the file-system caches.

      For data being read once and discarded, this option can improve performance.

      Available in iOS 4.0 and later.

    • DataReadingMappedAlways

      NSDataReadingMappedAlways

      Hint to map the file in if possible.

      This takes precedence over NSDataReadingMappedIfSafe if both are given.

      Available in iOS 5.0 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Options for methods used to Base-64 encode data.

    Declaration

    Swift

    struct NSDataBase64EncodingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var Encoding64CharacterLineLength: NSDataBase64EncodingOptions { get } static var Encoding76CharacterLineLength: NSDataBase64EncodingOptions { get } static var EncodingEndLineWithCarriageReturn: NSDataBase64EncodingOptions { get } static var EncodingEndLineWithLineFeed: NSDataBase64EncodingOptions { get } }

    Objective-C

    enum { NSDataBase64Encoding64CharacterLineLength = 1UL << 0, NSDataBase64Encoding76CharacterLineLength = 1UL << 1, NSDataBase64EncodingEndLineWithCarriageReturn = 1UL << 4, NSDataBase64EncodingEndLineWithLineFeed = 1UL << 5, }; typedef NSUInteger NSDataBase64EncodingOptions;

    Constants

    • Encoding64CharacterLineLength

      NSDataBase64Encoding64CharacterLineLength

      Set the maximum line length to 64 characters, after which a line ending is inserted.

      Available in iOS 7.0 and later.

    • Encoding76CharacterLineLength

      NSDataBase64Encoding76CharacterLineLength

      Set the maximum line length to 76 characters, after which a line ending is inserted.

      Available in iOS 7.0 and later.

    • EncodingEndLineWithCarriageReturn

      NSDataBase64EncodingEndLineWithCarriageReturn

      When a maximum line length is set, specify that the line ending to insert should include a carriage return.

      Available in iOS 7.0 and later.

    • EncodingEndLineWithLineFeed

      NSDataBase64EncodingEndLineWithLineFeed

      When a maximum line length is set, specify that the line ending to insert should include a line feed.

      Available in iOS 7.0 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later.

  • Options to modify the decoding algorithm used to decode Base-64 encoded NSData objects.

    Declaration

    Swift

    struct NSDataBase64DecodingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var IgnoreUnknownCharacters: NSDataBase64DecodingOptions { get } }

    Objective-C

    enum { NSDataBase64DecodingIgnoreUnknownCharacters = 1UL << 0 }; typedef NSUInteger NSDataBase64DecodingOptions;

    Constants

    • IgnoreUnknownCharacters

      NSDataBase64DecodingIgnoreUnknownCharacters

      Modify the decoding algorithm so that it ignores unknown non-Base-64 bytes, including line ending characters.

      Available in iOS 7.0 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 7.0 and later.

  • Deprecated names for reading options. Do not use these names, use the new replacements instead.

    Declaration

    Swift

    struct NSDataReadingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var DataReadingMappedIfSafe: NSDataReadingOptions { get } static var DataReadingUncached: NSDataReadingOptions { get } static var DataReadingMappedAlways: NSDataReadingOptions { get } static var DataReadingMapped: NSDataReadingOptions { get } static var MappedRead: NSDataReadingOptions { get } static var UncachedRead: NSDataReadingOptions { get } }

    Objective-C

    enum { NSDataReadingMapped = NSDataReadingMappedIfSafe, NSMappedRead = NSDataReadingMapped, NSUncachedRead = NSDataReadingUncached };

    Constants

  • Options for methods used to write NSData objects.

    Declaration

    Swift

    struct NSDataWritingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var DataWritingAtomic: NSDataWritingOptions { get } static var DataWritingWithoutOverwriting: NSDataWritingOptions { get } static var DataWritingFileProtectionNone: NSDataWritingOptions { get } static var DataWritingFileProtectionComplete: NSDataWritingOptions { get } static var DataWritingFileProtectionCompleteUnlessOpen: NSDataWritingOptions { get } static var DataWritingFileProtectionCompleteUntilFirstUserAuthentication: NSDataWritingOptions { get } static var DataWritingFileProtectionMask: NSDataWritingOptions { get } static var AtomicWrite: NSDataWritingOptions { get } }

    Objective-C

    enum { NSDataWritingAtomic = 1UL << 0, NSDataWritingWithoutOverwriting = 1UL << 1, NSDataWritingFileProtectionNone = 0x10000000, NSDataWritingFileProtectionComplete = 0x20000000, NSDataWritingFileProtectionCompleteUnlessOpen = 0x30000000, NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication = 0x40000000, NSDataWritingFileProtectionMask = 0xf0000000, }; typedef NSUInteger NSDataWritingOptions;

    Constants

    • DataWritingAtomic

      NSDataWritingAtomic

      A hint to write data to an auxiliary file first and then exchange the files. This option is equivalent to using a write method taking the parameter atomically:YES.

      Available in iOS 4.0 and later.

    • DataWritingWithoutOverwriting

      NSDataWritingWithoutOverwriting

      Hint to return prevent overwriting an existing file. Cannot be combined with NSDataWritingAtomic.

      Available in iOS 6.0 and later.

    • DataWritingFileProtectionNone

      NSDataWritingFileProtectionNone

      A hint to set the content protection attribute of the file when writing it out. In this case, the file is not stored in an encrypted format and may be accessed at boot time and while the device is unlocked.

      Available in iOS 4.0 and later.

    • DataWritingFileProtectionComplete

      NSDataWritingFileProtectionComplete

      A hint to set the content protection attribute of the file when writing it out. In this case, the file is stored in an encrypted format and may be read from or written to only while the device is unlocked. At all other times, attempts to read and write the file result in failure.

      Available in iOS 4.0 and later.

    • DataWritingFileProtectionCompleteUnlessOpen

      NSDataWritingFileProtectionCompleteUnlessOpen

      A hint to set the content protection attribute of the file when writing it out. In this case, the file cannot be opened for reading or writing when the device is locked, although new files can be created with this class. If one of these files is open when the device is locked, reading and writing are still allowed.

      Available in iOS 5.0 and later.

    • DataWritingFileProtectionCompleteUntilFirstUserAuthentication

      NSDataWritingFileProtectionCompleteUntilFirstUserAuthentication

      A hint to set the content protection attribute of the file when writing it out. In this case, the file can be read or written to while the device is locked, but while it is booting up, they have protection equivalent to NSDataWritingFileProtectionComplete.

      Available in iOS 5.0 and later.

    • DataWritingFileProtectionMask

      NSDataWritingFileProtectionMask

      A mask to use when determining the file protection options assigned to the data.

      Available in iOS 4.0 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.

  • Deprecated names for writing options. Do not use these names, use the new replacements instead.

    Declaration

    Swift

    struct NSDataWritingOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var DataWritingAtomic: NSDataWritingOptions { get } static var DataWritingWithoutOverwriting: NSDataWritingOptions { get } static var DataWritingFileProtectionNone: NSDataWritingOptions { get } static var DataWritingFileProtectionComplete: NSDataWritingOptions { get } static var DataWritingFileProtectionCompleteUnlessOpen: NSDataWritingOptions { get } static var DataWritingFileProtectionCompleteUntilFirstUserAuthentication: NSDataWritingOptions { get } static var DataWritingFileProtectionMask: NSDataWritingOptions { get } static var AtomicWrite: NSDataWritingOptions { get } }

    Objective-C

    enum { NSAtomicWrite = NSDataWritingAtomic };

    Constants

    • AtomicWrite

      NSAtomicWrite

      Deprecated name for NSDataWritingAtomic.

      Available in iOS 2.0 and later.

  • Options for method used to search NSData objects. These options are used with the rangeOfData:options:range: method.

    Declaration

    Swift

    struct NSDataSearchOptions : RawOptionSetType { init(_ rawValue: UInt) init(rawValue rawValue: UInt) static var Backwards: NSDataSearchOptions { get } static var Anchored: NSDataSearchOptions { get } }

    Objective-C

    enum { NSDataSearchBackwards = 1UL << 0, NSDataSearchAnchored = 1UL << 1 }; typedef NSUInteger NSDataSearchOptions;

    Constants

    • Backwards

      NSDataSearchBackwards

      Search from the end of NSData object.

      Available in iOS 4.0 and later.

    • Anchored

      NSDataSearchAnchored

      Search is limited to start (or end, if NSDataSearchBackwards) of NSData object.

      This option performs searching only on bytes at the beginning or end of the range. No match at the beginning or end means nothing is found, even if a matching sequence of bytes occurs elsewhere in the data object.

      Available in iOS 4.0 and later.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in iOS 4.0 and later.