如何取消分配从Swift结构引用的UnsafeMutablePointer [英] How to dealloc UnsafeMutablePointer referenced from Swift struct
本文介绍了如何取消分配从Swift结构引用的UnsafeMutablePointer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有这样的Swift结构:
If I have a Swift struct like this:
struct ViewBox {
let pointer: UnsafeMutablePointer<UIView>
init() {
pointer = UnsafeMutablePointer<UIView>.alloc(1)
}
}
当结构被释放时,我应该如何确保指针被正确地释放?我不能对Swift结构使用deinit
或dealloc
方法.
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()
}
这篇关于如何取消分配从Swift结构引用的UnsafeMutablePointer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文