Swift中如何管理内存?

本文和大家分享的主要是swift 中内存管理相关内容,一起来看看吧,希望对大家  学习swift有所帮助。
  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 ,就必须标记。
来源: 稀土掘金
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值