简体   繁体   中英

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?

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM