Swift-内存管理,指针

内存管理

  • Swift采用引用计数的ARC内存管理方案(堆空间)
  • Swift的ARC中有3钟引用
    • 强引用
    • 弱引用(weak reference)
    • 必须是可先类型的var,因为实例销毁后,ARC会自动弱引用设置为nil
    • ARC自动给弱引用设置nil时。不会触发属性观察器
    • 无主引用(unowned reference)
    • 不会产生强引用,实例销毁后仍然存储着实例的内存地址(类似于OC中的unsafe_unretained)
    • 在实例销毁后访问无主引用,会产生运行时错误(野指针)

循环引用

  • weak, unowned都能解决循环引用问题,unowned要比weak少一些性能消耗
    • 在生命周期可能会变为nil的使用weak
    • 初始化后再也不会变为nil的使用unowned

闭包的循环引用

  • 闭包表达式默认会对用到的外层对象产生额外的强引用,在闭包表达式的捕获变量声明weak或unowned引用,解决循环引用问题

@escaping逃逸闭包

  • 逃逸闭包:闭包有可能在函数结束后调用,闭包调用逃离了函数的作用域,需要通过@escaping声明
  • 非逃逸闭包:闭包调用发生在函数结束前,闭包调用在函数作用域内
// fn是非逃逸闭包
func test1(_ fn: Fn) { fn() }
// fn是逃逸闭包
var gFn: Fn?
func test2(_ fn: @escaping Fn) { gFn = fn }
// fn是逃逸闭包
func test3(_ fn: @escaping Fn) {
   DispatchQueue.global().async {
       fn()
   }
}
class Person {
   var fn: Fn
   // fn是逃逸闭包
   init(fn: @escaping Fn) {
       self.fn = fn
   }
   func run() {
       // DispatchQueue.global().async也是一个逃逸闭包
       // 它用到了实例成员(属性、方法),编译器会强制要求明确写出self
       DispatchQueue.global().async {
           self.fn()
       }
   }
}
  • 逃逸闭包不可以捕获inout参数
typealias Fn = () -> ()
func other1(_ fn: Fn) { fn() }
func other2(_ fn: @escaping Fn) { fn() }
func test(value: inout Int) -> Fn {
    other1 { value += 1 }
    // error: 逃逸闭包不能捕获inout参数
    other2 { value += 1 }
    func plus() { value += 1 }
    // error: 逃逸闭包不能捕获inout参数
    return plus
}

指针

  • UnsafePointer 类似于 const Pointee *
  • UnsafeMutablePointer 类似于 Pointee *
  • UnsafeRawPointer 类似于 const void *
  • UnsafeMutableRawPointer 类似于 void *
var age = 10
func test1(_ ptr: UnsafeMutablePointer) {
    ptr.pointee += 10
}

func test2(_ ptr: UnsafePointer) {
    // ptr.pointee += 10 错误
    print(ptr.pointee)
}

func test3(_ ptr: UnsafeMutableRawPointer) {
    ptr.storeBytes(of: 20, as: Int.self)
}

func test4(_ ptr: UnsafeRawPointer) {
//    ptr.storeBytes(of: 20, as: Int.self) 错误
    print(ptr.load(as: Int.self))
}

获得指向某个变量的指针

var age = 11
var ptr1 = withUnsafeMutablePointer(to: &age ) { $0 }
var ptr2 = withUnsafePointer(to: &age, { $0 })
ptr1.pointee = 22
print(ptr2.pointee) // 22
print(age) // 22

var ptr3 = withUnsafeMutablePointer(to: &age, { UnsafeMutableRawPointer($0) })
var ptr4 = withUnsafePointer(to: age, { UnsafeRawPointer($0) })
ptr3.storeBytes(of: 33, as: Int.self) // 33
print(age) // 3

获得指向堆空实例的指针

class Person {}
var person = Person()
var ptr5 = withUnsafePointer(to: &person) { UnsafeRawPointer($0) }
var heapPtr = UnsafeRawPointer(bitPattern: ptr5.load(as: UInt.self))
print(heapPtr)

创建指针

var ptr = UnsafeMutableRawPointer.allocate(byteCount: 16, alignment: 1)
ptr.storeBytes(of: 11, as: Int.self)
ptr.advanced(by: 8).storeBytes(of: 22, as: Int.self)
print(ptr.load(as: Int.self)) // 11
print(ptr.advanced(by: 8).load(as: Int.self)) // 22
ptr.deallocate()

do {
    var ptr = UnsafeMutablePointer.allocate(capacity: 3)
    ptr.initialize(to: 11)
    ptr.successor().initialize(to: 22)
    ptr.successor().successor().initialize(to: 33)
    print(ptr.pointee) // 11
    print((ptr + 1).pointee) // 22
    print((ptr + 2).pointee) // 33
    print(ptr[0]) // 11
    print(ptr[1]) // 22
    print(ptr[2]) // 33
    ptr.deinitialize(count: 3)
    ptr.deallocate()
}

do {
    class Person {
        var age: Int
        var name: String
        init(age: Int, name: String) {
            self.age = age
            self.name = name
        }
        deinit { print(name, "deinit") }
    }
    var ptr = UnsafeMutablePointer.allocate(capacity: 3)
    ptr.initialize(to: Person(age: 10, name: "Jack"))
    (ptr + 1).initialize(to: Person(age: 11, name: "Rose"))
    (ptr + 2).initialize(to: Person(age: 12, name: "Kate"))
    // Jack deinit
    // Rose deinit
    // Kate deinit
    ptr.deinitialize(count: 3)
    ptr.deallocate()
}

你可能感兴趣的:(Swift-内存管理,指针)