memory management attribute when using Class type property in Objective-C ARC? [duplicate]

孤者浪人 提交于 2019-12-11 17:08:21

问题


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?


回答1:


In Objective-C Class is an object and is instance of a metaclass. It is a retainable object pointer type. Reference: clang.llvm.org also this SO thread.




回答2:


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

Lets see different scenario 1.

Human.init(name: "Arjun")

OUTPUT:

// - Allocate Human

// - Deallocate Human

// Its automatically deallocate because its manage by ARC.

2.

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

OUTPUT

// - Allocate Human

//Its not deallocate automatically because human class reference count 1 (objHuman1)

 objHuman1 = nil

OUTPUT

// - Deallocate Human

//Because its referece count is 0

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

OUTPUT

Allocate Human

Allocate Passport

// Here is magic You can not deallocate passport. Because Human class has Storng reference of Passport.

// But if you declare Weak property of passport variable in Human Class Like:

weak var passport:Passport!

OUTPUT Will

//Allocate Human

//Allocate Passport

//Deallocate Passport

That's a magic of Week and Strong property. Swift Default property is Strong.



来源:https://stackoverflow.com/questions/53699976/memory-management-attribute-when-using-class-type-property-in-objective-c-arc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!