标签:
Swift使用自动引用计数(ARC)来管理应用程序的内存使用。在大多是情况下,并不需要考虑内存的管理。当实例不再需要的时候,ARC会自动释放这些实例所使用的内存。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
class Teacher { var tName : String var student : Student ? init (name: String ){ tName = name println ( "老师\(tName)实例初始化完成" ) } deinit{ println ( "老师\(tName)实例反初始化完成" ) } } class Student { var sName : String var teacher : Teacher ? init (name: String ){ sName = name println ( "学生\(sName)实例初始化完成" ) } deinit{ println ( "学生\(sName)实例反初始化完成" ) } } //测试开始 var teacher: Teacher ? var student: Student ? teacher = Teacher (name: "李老师" ) student = Student (name: "刘同学" ) teacher!.student = student student!.teacher = teacher teacher = nil student = nil //测试结果(deinit未调用,则内存泄露) 老师李老师实例初始化完成 学生刘同学实例初始化完成 |
解决办法:使用弱引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
class Teacher { var tName : String weak var student : Student ? init (name: String ){ tName = name println ( "老师\(tName)实例初始化完成" ) } deinit{ println ( "老师\(tName)实例反初始化完成" ) } } class Student { var sName : String var teacher : Teacher ? init (name: String ){ sName = name println ( "学生\(sName)实例初始化完成" ) } deinit{ println ( "学生\(sName)实例反初始化完成" ) } } |
2,闭包引起的循环强引用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
class JsonElement { let name: String let jValue: String ? lazy var asJson:() -> String = { if let text = self .jValue { return "\(self.name):\(text)" } else { return "text is nil" } } init (name: String , text: String ){ self .name = name self .jValue = text println ( "初始化闭包" ) } deinit{ println ( "闭包释放" ) } } //开始测试 var p: JsonElement ? = JsonElement (name: "p" , text: "hangge.com" ) println (p!.asJson()) p = nil //测试结果(deinit未调用,则内存泄露) 初始化闭包 p:hangge.com |
解决办法:使用闭包捕获列表
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
class JsonElement { let name: String let jValue: String ? lazy var asJson:() -> String = { [ unowned self ] in //使用无主引用来解决强引用循环 if let text = self .jValue { return "\(self.name):\(text)" } else { return "text is nil" } } init (name: String , text: String ){ self .name = name self .jValue = text println ( "初始化闭包" ) } deinit{ println ( "闭包释放" ) } } |
标签:
原文地址:http://www.cnblogs.com/Free-Thinker/p/4841131.html