memory management attribute when using Class type

2019-08-27 21:47发布

This question already has an answer here:

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?

2条回答
孤傲高冷的网名
2楼-- · 2019-08-27 21:59

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.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-08-27 22:10
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.

查看更多
登录 后发表回答