在Objective-C ARC中使用“类类型"属性时的内存管理属性? [英] memory management attribute when using Class type property in Objective-C ARC?
问题描述
Class
是结构指针,是对象类型还是标量,我猜这是决定使用strong
/weak
或assign
的关键吗?
Class
is a struct pointer, is it a object type or scalar, which I guess is the key to decide to use strong
/weak
or assign
?
推荐答案
import UIKit
class Human{
var name:String!
var passport:Passport!
// weak var passport:Passport!
init(name:String) {
self.name = name
print("Allocate Human")
}
deinit {
print("Deallocate Human")
}
}
class Passport {
var country:String!
var human:Human!
init(country:String) {
self.country = country
print("Allocate Passport")
}
deinit {
print("Deallocate Passport")
}
}
让我们看到不同的情况 1.
Human.init(name: "Arjun")
输出:
//-分配人类
//-取消分配人
//它自动取消分配,因为它由ARC管理.
// Its automatically deallocate because its manage by ARC.
2.
var objHuman1: Human? = Human.init(name: "Arjun")
输出
//-分配人类
//它不会自动取消分配,因为人类类引用计数为1(objHuman1)
//Its not deallocate automatically because human class reference count 1 (objHuman1)
objHuman1 = nil
输出
//-取消分配人
//因为它的推荐计数为0
//Because its referece count is 0
var passport: Passport? = Passport.init(country: "India")
objHuman1?.passport = passport
passport = nil
输出
分配人
分配护照
//这很神奇您不能取消分配护照.因为人类"类有Storng的Passport参考.
//但是,如果在Human Class中声明护照变量的弱属性,如:
// But if you declare Weak property of passport variable in Human Class Like:
weak var passport:Passport!
输出将
//分配人
//分配护照
//取消分配护照
这是Week和Strong属性的魔力. Swift默认属性为强".
That's a magic of Week and Strong property. Swift Default property is Strong.
这篇关于在Objective-C ARC中使用“类类型"属性时的内存管理属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!