Swift iOS : 内存管理

栏目: Swift · 发布时间: 6年前

内容简介:Swift iOS : 内存管理

Swift是自动管理内存的。这意味着,你不需要主动释放内存。

比如Foo内包含的Bar,可以随同Foo一起被释放:

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        Foo()
        return true
    }
}
class Foo {
    let bar: Bar
    init() {
        bar = Bar()
    }
    deinit {
        print("Foo exit")
    }
}
class Bar {
    deinit {
        print("Bar exit")
    }
}

执行此代码,会打印:

Foo exit
Bar exit

可见Foo和Bar都是自动释放的。作为程序员,你不需要做任何内存的主动释放。

但是,有一种特殊情况,叫做双向引用,导致释放A时,需要释放B,而B又引用了A,那么两个都无法被释放:

class Foo {
    let bar: Bar
    init() {
        bar = Bar()
        bar.foo = self
    }

    deinit {
        print("Foo exit")
    }
}
class Bar {
    var foo: Foo? = nil
    deinit {
        print("Bar exit")
    }
}

此代码只会打印:

App exit

此时,需要做的就是把这个双向引用中的一个设置为weak,表示的意思是尽管我持有这个引用,但是释放的时候,却无需考虑此对象的释放。

import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
    var window : UIWindow?
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        Baz()
        print("App exit")
        return true
    }
}
typealias Bar = (()->Void)
class Foo {
    func work(_ bar : Bar) {
        bar()
    }

    deinit {
        print("Foo exit")
    }
}
class Baz {
    var a : String?
    init (){
        a = "1"
        let f = Foo()
        f.work(){[weak self]() in
            print(self?.a)
        }
    }
}

当然,不标记也是不行的,因为编译器就不会通过,它要求只要引用了self,就必须标记。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Measure What Matters

Measure What Matters

John Doerr / Portfolio / 2018-4-24 / GBP 19.67

In the fall of 1999, John Doerr met with the founders of a start-up he’d just given $11.8 million, the biggest investment of his career. Larry Page and Sergey Brin had amazing technology, entrepreneur......一起来看看 《Measure What Matters》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

URL 编码/解码
URL 编码/解码

URL 编码/解码