内存管理

2019-07-31  本文已影响0人  曹来东
  1. 必须是可选类型的var因为实例销毁后,ARC会自动将弱引用设置为nil
    2.ARC自动给弱引用设置nil时,不会触发属性观察器

weak unowned的使用限制

public 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>(involing body: () throws -> Result) rethrows -> Result

autoreleasepool {
    let p = Person(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()
    }
}
class Person {
    var fn: (() -> ())?
    func run() {
        print("run")
    }
    deinit {
        print("deinit")
    }
    
}

func test() {
    let p = Person()
    p.fn = { [weak p] in
        p?.run()
    }
}

func test() {
    let p = Person()
    p.fn = { [unowned p] in
        p.run()
    }
}

p.fn = {
    [weak wp = p,unowned up = p , a = 10 + 20] in
    wp?.run()
}
class Person {
    lazy var fn: (() -> ()) = {
        [weak self] in
        self?.run()
    }
    func run() {
        print("run")
    }
    deinit {
        print("deinit")
    }
}
class Person {
    var age: Int = 0
    lazy var getAge: Int = {
        self.age
    }()
    deinit {
        print("deinit")
    }
}

@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()
        }
    }  
}

逃逸闭包的注意点

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 0x100001030, but modification requires exclusive access.
var step = 1
func increment(_ num: inout Int) { num += step}
increment(&step)
var step = 1
func increment(_ num: inout Int) { num += step}

var copyOfStep = step
increment(&copyOfStep)
step = copyOfStep
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
//Inout arguments are not allowed to alias each other
//Overlapping accesses to 'num1', but modification requires exclusive access; consider copying to a local variable
balance(&num1, &num1)//Error
func balance(_ x: inout Int,_ y: inout Int) {
    let sum = x + y
    x = sum / 2
    y = sum - x
    
}
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
var tuple = (health: 10 ,energy: 20)
//Error
balance(&tuple.health, &tuple.energy)

var holly = Player(name: "Holly", health: 10, energy: 10)
//Error
balance(&holly.health, *holly.energy)
func balance(_ x: inout Int,_ y: inout Int) {
    let sum = x + y
    x = sum / 2
    y = sum - x
    
}
struct Player {
    var name: String
    var health: Int
    var energy: Int
    mutating func shareHealth(with teammate: inout Player) {
        balance(&teammate.health, &health)
    }
}
func test() {
    var tuple = (health: 10,energy: 20)
    balance(&tuple.health, &tuple.energy)
    
    var holly = Player(name: "Holly", health: 10, energy: 10)
    balance(&holly.health, &holly.energy)
}
test()
上一篇下一篇

猜你喜欢

热点阅读