Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 862
JAL Avatar asked Jan 28 '26 14:01

JAL


1 Answers

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.

like image 142
Martin R Avatar answered Jan 31 '26 06:01

Martin R



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!