Swift iOS : 内存管理

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

内容简介: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,就必须标记。


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

查看所有标签

猜你喜欢:

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

Advanced Web Metrics with Google Analytics

Advanced Web Metrics with Google Analytics

Brian Clifton / Sybex / 2008 / USD 39.99

Are you getting the most out of your website? Google insider and web metrics expert Brian Clifton reveals the information you need to get a true picture of your site's impact and stay competitive usin......一起来看看 《Advanced Web Metrics with Google Analytics》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具