Contents

NSData

A static byte buffer in memory.

Declaration

class NSData

Mentioned in

Overview

In Swift, the buffer bridges to Data; use NSData when you need reference semantics or other Foundation-specific behavior.

NSData and its mutable subclass NSMutableData provide data objects, or 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.

The size of the data is subject to a theoretical limit of about 8 exabytes (1 EB = 10¹⁸ bytes; in practice, the limit should not be a factor).

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

Writing Data Atomically

NSData provides methods for atomically saving their contents to a file, which guarantee that the data is either saved in its entirety, or it fails completely. An atomic write first writes the data to a temporary file and then, only if this write succeeds, moves the temporary file to its final location.

Although 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. When you work with a publicly accessible file, 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 write(to:atomically:) method (and the related methods) when working inside a publicly accessible directory. Instead, use FileHandle with an existing file descriptor to securely write the file.

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

Topics

Creating Data

Reading Data from a File

Writing Data to a File

Encoding and Decoding Base64 Representations

Accessing Underlying Bytes

Finding Data

Testing Data

Describing Data

Compressing and Decompressing Data

Initializers

Default Implementations