内容简介: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,就必须标记。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
深入浅出Struts 2
Budi Kuniawan / 杨涛、王建桥、杨晓云 / 人民邮电出版社 / 2009-04 / 59.00元
本书是广受赞誉的Struts 2优秀教程,它全面而深入地阐述了Struts 2的各个特性,并指导开发人员如何根据遇到的问题对症下药,选择使用最合适的特性。作者处处从实战出发,在丰富的示例中直观地探讨了许多实用的技术,如数据类型转换、文件上传和下载、提高Struts 2应用的安全性、调试与性能分析、FreeMarker、Velocity、Ajax,等等。跟随作者一道深入Struts 2,聆听大量来之......一起来看看 《深入浅出Struts 2》 这本书的介绍吧!