Swift中如何管理内存?

来源:互联网 发布:spss19.0破解软件 编辑:程序博客网 时间:2024/05/16 07:34
本文和大家分享的主要是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 ,就必须标记。
来源: 稀土掘金
原创粉丝点击