Is it necessary to deallocate an AutoreleasingUnsafeMutablePointer? If so, how?

Viewed 1201

With ARC, I can just set all of an object's strong references to nil to deallocate it.

With an UnsafePointer or UnsafeMutablePointer, I need to manage its memory explicitly:

let buffer = sizeof(Int8) * 4
var ptr = UnsafeMutablePointer<Void>.alloc(buffer)
defer {
    ptr.destroy()
    ptr.dealloc(someVal)
    ptr = nil
}

But the documentation is ambiguous for AutoreleasingUnsafeMutablePointer objects. I cannot explicitly call destroy or dealloc on a AutoreleasingUnsafeMutablePointer.

var ptr: AutoreleasingUnsafeMutablePointer<Void> = nil
defer {
    ptr = nil
}

// assign something to ptr

The name implies that it is autoreleased after it falls out of scope, but do I need to set a AutoreleasingUnsafeMutablePointer to nil in order for it to be autoreleased?

Here's an example where I use an AutoreleasingUnsafeMutablePointer to get a list of all of the classes currently loaded by the runtime. Note that when invoking the power of the Objective-C runtime some functions require a AutoreleasingUnsafeMutablePointer rather than just a UnsafeMutablePointer:

var numClasses: Int32 = 0
var allClasses: AutoreleasingUnsafeMutablePointer<AnyClass?> = nil
defer {
    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)")
        }
    }
}
1 Answers
Related