A static byte buffer in memory.
SDKs
- iOS 2.0+
- macOS 10.0+
- Mac Catalyst 13.0+
- tvOS 9.0+
- watchOS 2.0+
Framework
- Foundation
Declaration
@interface NSData : NSObject
Overview
NSData and its mutable subclass NSMutable
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.
Important
The Swift overlay to the Foundation framework provides the Data
structure, which bridges to the NSData
class and its mutable subclass NSMutable
. For more information about value types, see Working with Cocoa Frameworks in Using Swift with Cocoa and Objective-C (Swift 4.1).
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
method (and the related methods) when working inside a publicly accessible directory. Instead, use NSFile
with an existing file descriptor to securely write the file.
For more information, see Securing File Operations in Secure Coding Guide.