Search code examples
swiftunsafe-pointers

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


Consider this extension on NSData which serializes an NSData 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 UnsafeBufferPointer 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 UnsafePointer from the memory of the bytes of an NSData object, do I need to make sure to destroy that pointer after the buffer is copied?


Solution

  • UnsafePointer(self.bytes) is only a pointer conversion from UnsafePointer<Void> to UnsafePointer<UInt8> (like a "cast" in C). It does not allocate memory.

    The memory is managed by the NSData object. You did not alloc() the memory and therefore must not call dealloc() on the pointer. You also did not initialize() the memory and therefore must not destroy() it.