使用UnsafePointer或UnsafeMutablePointer,我需要显式管理其内存:
let buffer = sizeof(Int8) * 4var ptr = UnsafeMutablePointer<VoID>.alloc(buffer)defer { ptr.destroy() ptr.dealloc(someVal) ptr = nil}
但是对于autoreleasingUnsafeMutablePointer对象,文档是不明确的.我无法在autoreleasingUnsafeMutablePointer上显式调用destroy或dealloc.
var ptr: autoreleasingUnsafeMutablePointer<VoID> = nildefer { ptr = nil}// assign something to ptr
该名称暗示它在超出范围后自动释放,但是我是否需要将autoreleasingUnsafeMutablePointer设置为nil才能自动释放?
这是一个示例,我使用autoreleasingUnsafeMutablePointer来获取运行时当前加载的所有类的列表.请注意,在调用Objective-C运行时的功能时,某些函数需要autoreleasingUnsafeMutablePointer而不仅仅是UnsafeMutablePointer:
var numClasses: Int32 = 0var allClasses: autoreleasingUnsafeMutablePointer<AnyClass?> = nildefer { allClasses = nil // is this required?}numClasses = objc_getClassList(nil,0)if numClasses > 0 { var ptr = UnsafeMutablePointer<AnyClass>.alloc(Int(numClasses)) defer { ptr.destroy() ptr.dealloc(Int(numClasses)) ptr = nil } allClasses = autoreleasingUnsafeMutablePointer<AnyClass?>.init(ptr) numClasses = objc_getClassList(allClasses,numClasses) for i in 0 ..< numClasses { if let currentClass: AnyClass = allClasses[Int(i)] { print("\(currentClass)") } }}您不需要将其设置为nil.它应该由一个自动释放的指针构造(假设它被正确构造,它将自行释放).同时,不要抓住它超过当前的堆栈框架. autoreleasingUnsafeMutablePointer不会使对象保持活动状态.d出封闭的自动释放池时,将释放包装的对象并可能已取消分配.就像这个名字所说:它是不安全的.
通过永远不在Swift中自己创建autoreleasingUnsafeMutablePointer来避免问题(编辑:除非它真的是一个UnsafeMutablePointer并且C头导入出错了,见下文).如果你正确使用它,它应该是Swift的inout和Objective-C返回指针参数之间的透明胶水.
您通常会创建一个与所包含类型匹配的var,并将其传入inout.
例如如果你想调用这个函数:
func someFunction(obj: autoreleasingUnsafeMutablePointer<AnyObject?>)
然后你像这样调用它:
var myObject: AnyObject? = nilsomeFunction(&AnyObject)
一切都会好起来的.
我不知道你应该持有autoreleasingUnsafeMutablePointer的任何其他情况.我不认为你应该在Swift方面手动构建一个,除非是nil.在Swift中构建具有非零内容的autoreleasingUnsafeMutablePointer是非常困难的,因为自动释放的唯一方法是使用Unmanaged.
回应您的更新……
objc_getClassList函数签名是Swift自动C导入中的一个小故障.它错误地假设应该将Class *参数导入为autoreleasingUnsafeMutablePointer< AnyObject?>.你真的只需要一个可以从数组中获取的UnsafeMutablePointer:
var allClasses = Array<AnyClass?>(count: Int(objc_getClassList(nil,0)),repeatedValue: nil)allClasses.withUnsafeMutableBufferPointer { (inout bp: UnsafeMutableBufferPointer<AnyClass?>) in objc_getClassList(autoreleasingUnsafeMutablePointer(bp.baseAddress),Int32(allClasses.count))}总结
以上是内存溢出为你收集整理的swift – 是否有必要解除分配AutoreleasingUnsafeMutablePointer?如果是这样,怎么样?全部内容,希望文章能够帮你解决swift – 是否有必要解除分配AutoreleasingUnsafeMutablePointer?如果是这样,怎么样?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)