标签:swift
在swift 里引用循环的造成,主要有两个方法,
1.类之间的引用
2.clourse 闭包引用
解决办法:
weak references and unowned references. 也就是weak,unowned
weak, 来修饰可选的,? 结尾的,如:var weak city: String ?
unowned 来修身 一直存在的。 var unowned city: String
class Person { letname: String init(name:String) { self.name =name } var apartment: Apartment? deinit { println("\(name) is being deinitialized") } } class Apartment { letnumber: Int init(number:Int) { self.number =number } weak var tenant: Person? deinit { println("Apartment #\(number) is being deinitialized") } }weak 避免循环引用的例子
class Customer { letname: String var card: CreditCard? init(name:String) { self.name = name } deinit { println("\(name) is being deinitialized") } } class CreditCard { let number: UInt64 unowned let customer: Customer init(number:UInt64, customer: Customer) { self.number = number self.customer = customer } deinit { println("Card #\(number) is being deinitialized") } }
lazyvar someClosure: (Int,String) -> String = { [unownedself, weak delegate = self.delegate!] (index:Int, stringToProcess: String) -> String in // closure body goes here }
详情请看apple swift 文档
标签:swift
原文地址:http://blog.csdn.net/wenluma/article/details/45844537