Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dealloc UnsafeMutablePointer referenced from Swift struct

If I have a Swift struct like this:

struct ViewBox {
    let pointer: UnsafeMutablePointer<UIView>
    init() {
        pointer = UnsafeMutablePointer<UIView>.alloc(1)
    }
}

how should I ensure, that the pointer is properly deallocated, when the struct is deallocated? I can't use deinit or dealloc methods for Swift structs.

Or I don't have to care and it's happening automatically?

like image 494
VojtaStavik Avatar asked Apr 10 '26 16:04

VojtaStavik


1 Answers

You could wrap the pointer in a class. Something like this:

struct ViewBox {
    class WrappedPointer() {    
        let pointer: UnsafeMutablePointer<UIView>

        init() {
            pointer = UnsafeMutablePointer<UIView>.alloc(1)
        }

        deinit {
            pointer.dealloc(1)
        }
    }

    let wrappedPointer = WrappedPointer()
}
like image 100
Ole Begemann Avatar answered Apr 13 '26 07:04

Ole Begemann



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!