reference cycle 引用循环

前端之家收集整理的这篇文章主要介绍了reference cycle 引用循环前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在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") }
    }


以上 unowned 避免循环引用的例子
    lazyvar someClosure: (Int,String) -> String = {
    [unownedself,weak delegate = self.delegate!] (index:Int,stringToProcess: String) -> String in
    // closure body goes here
    }
clourse 中避免循环引用的例子


详情请看apple swift 文档

猜你在找的Swift相关文章