我想定义一个方法,当此类中的变量增加到某个值时,该方法可以销毁它所属的实例。我尝试执行以下操作:
var calledTimes = 0 //some other method would update this value
func shouldDestroySelf(){
if calledTimes == MAX_TIMES {
denit
}
}
但是我会收到错误消息,说"期望取消初始化器使用'{'"。
班里有自毁吗?
不能调用deinit
方法。来自苹果文档:Deinitializers are called automatically, just before instance deallocation takes place. You are not allowed to call a deinitializer yourself.
您应该将该实例设置为 nil
以便销毁该实例,前提是对该实例的所有引用都已断开。
您可以创建一个协议,该协议根据特定标准进行自我销毁。下面是一个使用类的示例
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()。基本思想是仅在一个位置拥有对象的所有权,然后在满足条件时分离所有权。在这种情况下,所有权是一个静态数组,分离是将其从数组中删除。需要注意的一件重要事情是,无论在哪里使用对象,都必须使用弱引用。
例如
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")
}
}
}