memory management attribute when using Class type

2019-08-27 21:40发布

问题:

This question already has an answer here:

  • Objective-C - Should we use strong, weak or assign for Class-type? 1 answer

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.