gpt4 book ai didi

ios - 在 Swift 中创建一个应用程序生命周期对象(不可能被释放)

转载 作者:行者123 更新时间:2023-11-28 12:22:36 24 4
gpt4 key购买 nike

我想从一个类中创建一个对象。我希望它的生命周期成为应用程序的生命周期。我的意思是我不希望它在应用程序运行时被释放。
我想从中创建实例的类:

extension Post {

@NSManaged var userId: Int
@NSManaged var id: Int
@NSManaged var title: String
@NSManaged var body: String

}

class Post: NSManagedObject {

// Insert code here to add functionality to your managed object subclass

override func awakeFromInsert() {
super.awakeFromInsert()
title = ""
userId = 0
id = 0
body = ""

}
}

最佳答案

不能释放指向自身的强指针的对象:

class Permanent {
private var ref: Permanent?

init() {
ref = self
}

deinit {
// This will never be called
print("Permanent deinit")
}
}

func test() {
var a = [Permanent(), Permanent()]
print(a.count)

print("free the items")
a = []
print("end of test")
}

test()

输出:

2
free the items
end of test

如果您注释掉 ref = self 行:

输出:

2
free the items
Permanent deinit
Permanent deinit
end of test

关于ios - 在 Swift 中创建一个应用程序生命周期对象(不可能被释放),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44352679/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com