在Objective-C ARC中使用“类类型”属性时的内存管理属性?

时间:2018-12-10 05:29:40

标签: ios objective-c automatic-ref-counting

Class是一个结构指针,是对象类型还是标量,我猜这是决定使用strong / weakassign的关键吗? / p>

2 个答案:

答案 0 :(得分:0)

在Objective-C中,类是一个对象,是元类的实例。它是一种可保留的对象指针类型。参考:clang.llvm.org也是这样的thread

答案 1 :(得分:0)

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管理,因此会自动取消分配。

2。

var objHuman1: Human? = Human.init(name: "Arjun")

输出

//-分配人类

//它不会自动取消分配,因为人类类引用计数为1(objHuman1)

 objHuman1 = nil

输出

//-取消分配人

//因为它的推荐计数为0

var passport: Passport? = Passport.init(country: "India")
objHuman1?.passport = passport
passport = nil

输出

分配人

分配护照

//这很神奇您不能取消分配护照。因为“人类”类具有Storng的Passport参考。

//但是,如果在Human Class中声明护照变量的弱属性,如:

weak var passport:Passport!

输出会

//分配人

//分配护照

//取消分配护照

这是Week和Strong属性的魔力。 Swift默认属性为“强”。