Swift语法 -- [20 - 内存管理]

2020-10-30  本文已影响0人  happy神悦

跟OC一样,Swift也是采取基于引用计数的ARC内存管理方案(针对堆空间)

Swift的ARC中有3种引用

1. weak、unowned的使用限制

protocol Livable : AnyObject {}
class Person {}
weak var p0: Person?
weak var p1: AnyObject?
weak var p2: Livable?
unowned var p10: Person?
unowned var p11: AnyObject?
unowned var p12: Livable?

2. Autoreleasepool

autoreleasepool {
    let p = MJPerson(age: 20, name: "Jack")
    p.run()
}

3. 循环引用(Reference Cycle)

weak、unowned 都能解决循环引用的问题,unowned 要比weak 少一些性能消耗

4. 闭包的循环引用

闭包表达式默认会对用到的外层对象产生额外的强引用

class Person {
    var fn: (() -> ())?
    func run() { print("run") }
    deinit { print("deinit") }
}
func test() {
    let p = Person()
    // 使用 weak 进行弱引用,在闭包内
    p.fn = {[weak p] in
        p?.run() 
    }
}
test()

5. 内存访问冲突(Conflicting Access to Memory)

内存访问冲突会在两个访问满足下列条件时发生:

 // 存在内存访问冲突
// Simultaneous accesses to 0x0, but modification requires exclusive access var step = 1
func increment(_ num: inout Int) { num += step }
increment(&step)

 // 解决内存访问冲突
var copyOfStep = step increment(&copyOfStep) step = copyOfStep

如果下面的条件可以满足,就说明重叠访问结构体的属性是安全的

 // Ok
func test() {
var tulpe = (health: 10, energy: 20) balance(&tulpe.health, &tulpe.energy)
var holly = Player(name: "Holly", health: 10, energy: 10)
balance(&holly.health, &holly.energy) }
test()

6. 指针

Swift中也有专门的指针类型,这些都被定性为“Unsafe”(不安全的),常见的有以下4种类型

var age = 10
func test1(_ ptr: UnsafeMutablePointer<Int>) {
    ptr.pointee += 10
}
func test2(_ ptr: UnsafePointer<Int>) { print(ptr.pointee)
}
test1(&age)
test2(&age) // 20
print(age) // 20

上一篇 下一篇

猜你喜欢

热点阅读