JAL JAL - 11 months ago 74
Swift Question

Do I need to release an UnsafeBufferPointer, or the UnsafePointer used at the buffer pointer's starting memory location?

Consider this extension on

which serializes an
object into a hex String:

extension NSData {
func base16EncodedString(uppercase uppercase: Bool = false) -> String {
let buffer = UnsafeBufferPointer<UInt8>(start: UnsafePointer(self.bytes), count: self.length)
let hexFormat = uppercase ? "X" : "x"
let formatString = "%02\(hexFormat)"
let bytesAsHexStrings = buffer.map {
String(format: formatString, $0)
return bytesAsHexStrings.joinWithSeparator("")

If an
is a non-owning pointer, does that mean I don't need to (or am not able to) explicitly call destroy? If I'm creating an
from the memory of the bytes of an
object, do I need to make sure to destroy that pointer after the buffer is copied?


UnsafePointer(self.bytes) is only a pointer conversion ("cast") from UnsafePointer<Void> to UnsafePointer<UInt8>. It does not allocate memory. The memory is managed by the NSData object. There is no need to call destroy and you definitely should not call dealloc on the pointer.