[Swift5.1] 20-内存管理

2020-06-06  本文已影响0人  codeTao

内存管理

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

Swift的ARC中有3种引用:
1)强引用(strong reference):默认情况下,引用都是强引用

2)弱引用(weak reference):通过weak定义弱引用

3)无主引用(unowned reference):通过unowned定义无主引用.

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?

Autoreleasepool

public func autoreleasepool<Result>(invoking body: () throws -> Result) rethrows -> Result
autoreleasepool {
    let p = MJPerson(age: 20, name: "Jack")
    p.run()
}

循环引用(Reference Cycle)

闭包的循环引用

class Person {
    var fn: (() -> ())?
    func run() { print("run") }
    deinit { print("deinit") }
}
func test() {
    let p = Person()
    p.fn = { p.run() }
}
test()

解决闭包的循环引用:
在闭包表达式的捕获列表声明weakunowned引用,解决循环引用问题

p.fn = {
    [weak p] in
    p?.run()
}
p.fn = {
    [unowned p] in
    p.run()
}
p.fn = {
    [weak wp = p, unowned up = p, a = 10 + 20] in
    wp?.run()
}

闭包的self

class Person {
    lazy var fn: (() -> ()) = {
        [weak self] in
        self?.run()
    }
    func run() { print("run") }
    deinit { print("deinit") }
}

func test(){
    var p = Person()
    p.fn()
}
test()
class Person {
    var age: Int = 0
//getAge本质是Int类型, 不是闭包
    lazy var getAge: Int = {
        self.age
    }()
    deinit { print("deinit") }
}

func test(){
    var p = Person()
    print(p.getAge)
}
test()

@escaping

非逃逸闭包、逃逸闭包,一般都是当做参数传递给函数:

import Dispatch
typealias Fn = () -> ()
// 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()
            //如果Person对象销毁不再执行闭包,可以这样写
            //[weak weakSelf = self] in 
            //weakSelf?.fn()
        }
    }
}

逃逸闭包的注意点

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
}

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

内存访问冲突会在两个访问满足下列条件时发生:
(在全局作用域中)

// 不存在内存访问冲突
func plus(_ num: inout Int) -> Int { num + 1 }
var number = 1
number = plus(&number)

存在内存访问冲突

// 存在内存访问冲突
// 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

内存访问冲突示例

1)同时访问同一变量内存地址

func balance(_ x: inout Int, _ y: inout Int) {
    let sum = x + y
    x = sum / 2
    y = sum - x
}
var num1 = 42
var num2 = 30
balance(&num1, &num2)    // OK
balance(&num1, &num1) // Error

2)同时访问同一对象属性内存地址

struct Player {
    var name: String
    var health: Int
    var energy: Int
    mutating func shareHealth(with teammate: inout Player) {
        balance(&teammate.health, &health)
    }
}
var oscar = Player(name: "Oscar", health: 10, energy: 10)
var maria = Player(name: "Maria", health: 5, energy: 10)
oscar.shareHealth(with: &maria)    // OK
oscar.shareHealth(with: &oscar) // Error 
//同时访问同一对象属性health内存地址

3)同时访问同一元组内存地址

var tulpe = (health: 10, energy: 20)
// Error
balance(&tulpe.health, &tulpe.energy)

var holly = Player(name: "Holly", health: 10, energy: 10)
// Error
balance(&holly.health, &holly.energy)
//health和energy在元组中属于同一块内存

内存访问冲突示例二

如果下面的条件可以满足,就说明重叠访问结构体的属性是安全的:
(在局部作用域中)

// 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()
上一篇 下一篇

猜你喜欢

热点阅读