How to dealloc UnsafeMutablePointer referenced from Swift struct

冷暖自知 提交于 2019-12-23 21:34:29

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/35986292/how-to-dealloc-unsafemutablepointer-referenced-from-swift-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!