NSData
A static byte buffer in memory.
Declaration
class NSDataMentioned 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
init(bytes:length:)init(bytesNoCopy:length:)init(bytesNoCopy:length:deallocator:)init(bytesNoCopy:length:freeWhenDone:)init(data:)
Reading Data from a File
init(contentsOfFile:)init(contentsOfFile:options:)NSData.ReadingOptionsinit(contentsOfMappedFile:)dataWithContentsOfMappedFile(_:)
Writing Data to a File
write(toFile:atomically:)write(toFile:options:)write(to:atomically:)write(to:options:)NSData.WritingOptions
Encoding and Decoding Base64 Representations
init(base64EncodedData:options:)init(base64Encoding:)init(base64EncodedString:options:)base64EncodedData(options:)base64EncodedString(options:)base64Encoding()NSData.Base64EncodingOptionsNSData.Base64DecodingOptions
Accessing Underlying Bytes
Finding Data
Testing Data
Describing Data
Compressing and Decompressing Data
compressed(using:)decompressed(using:)NSData.CompressionAlgorithmNSCompressionErrorMaximumNSCompressionErrorMinimumNSCompressionFailedErrorNSDecompressionFailedError
Initializers
init(base64Encoded:options:)init(base64Encoded:options:)init(coder:)init(contentsOf:)init(contentsOf:options:)