在Swift中创建应用程序生命周期对象(不可能被释放)
问题描述:
我想从一个类创建一个对象。而且我希望它能成为应用程序的一生。我的意思是我希望它不会因为应用程序正在运行而被释放。
,我想从做一个实例类:在Swift中创建应用程序生命周期对象(不可能被释放)
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
单身NSManagedObject子类没有意义。 – Paulw11
@ Paulw11帖子使用CoreData存储。 –