3

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?

Community
  • 1
  • 1
JAL
  • 41,701
  • 23
  • 172
  • 300
  • Compare http://stackoverflow.com/q/25605658/1187415: *"destroy() is only necessary if you have non-trivial content in the memory referred to by the pointer, such as a strong reference or a Swift struct or enum."* – In that sense, `UInt8` is "trivial content", and it is irrelevant if you call destroy or not. – Martin R Jul 26 '16 at 15:00
  • @MartinR thanks. So `UnsafePointer(self.bytes)` won't leak, since as soon as it falls out of scope it will be released? – JAL Jul 26 '16 at 15:08
  • 3
    `UnsafePointer(self.bytes)` is only a pointer conversion ("cast") from `UnsafePointer` to `UnsafePointer`. It does not allocate memory. The memory is managed by the `NSData` object. – Martin R Jul 26 '16 at 15:12
  • @MartinR Ah of course, because we're not calling alloc. Thanks. If you add this as an answer I'll accept it. – JAL Jul 26 '16 at 15:14

1 Answers1

5

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.

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382