码迷,mamicode.com
首页 > 其他好文 > 详细

reference cycle 引用循环

时间:2015-05-19 16:43:14      阅读:165      评论:0      收藏:0      [点我收藏+]

标签: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") }
    }


以上 unowned 避免循环引用的例子

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


详情请看apple swift 文档



reference cycle 引用循环

标签:swift

原文地址:http://blog.csdn.net/wenluma/article/details/45844537

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!