我想定义一个方法,当该类中的变量增加到某个值时,该方法可以销毁它所属的实例。我试图做以下事情:
var calledTimes = 0 //some other method would update this value
func shouldDestroySelf(){
if calledTimes == MAX_TIMES {
denit
}
}
但我会收到错误消息说" Expect' {'对于deinitializers"。
在课堂上有没有自毁?
答案 0 :(得分:3)
您无法调用deinit
方法。来自Apple Docs:Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself.
您应该将该实例设置为nil
,以便在该实例的所有引用都被破坏的情况下销毁该实例。
答案 1 :(得分:2)
您可以创建一个基于特定条件进行自毁的协议。这是使用类
的示例class SelfDestructorClass
{
var calledTimes = 0
let MAX_TIMES=5
static var instancesOfSelf = [SelfDestructorClass]()
init()
{
SelfDestructorClass.instancesOfSelf.append(self)
}
class func destroySelf(object:SelfDestructorClass)
{
instancesOfSelf = instancesOfSelf.filter {
$0 !== object
}
}
deinit {
print("Destroying instance of SelfDestructorClass")
}
func call() {
calledTimes += 1
print("called \(calledTimes)")
if calledTimes > MAX_TIMES {
SelfDestructorClass.destroySelf(self)
}
}
}
您可以从此类派生您的类,然后在这些对象上调用call()。基本思想是仅在一个地方拥有对象的所有权,然后在满足标准时分离所有权。在这种情况下,所有权是一个静态数组,并且分离是从数组中删除它。需要注意的一件重要事情是,无论您在何处使用它,都必须使用弱引用。
E.g。
class ViewController: UIViewController {
weak var selfDestructingObject = SelfDestructorClass()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func countDown(sender:AnyObject?)
{
if selfDestructingObject != nil {
selfDestructingObject!.call()
} else {
print("object no longer exists")
}
}
}