在Objective-C ARC中使用“类类型"属性时的内存管理属性? [英] memory management attribute when using Class type property in Objective-C ARC?

查看:82
本文介绍了在Objective-C ARC中使用“类类型"属性时的内存管理属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆