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.


init(bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int, deallocator: ((UnsafeMutableRawPointer, Int) -> Void)? = nil)



A buffer containing data for the new object.


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


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.


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.