特定の基準に基づいて自己破壊を行うプロトコルを作成できます。クラスを使用した例を次に示します
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() を呼び出すことができます。基本的な考え方は、オブジェクトの所有権を 1 か所だけに限定し、基準が満たされたときに所有権を切り離すことです。この場合の所有権は静的配列であり、デタッチはそれを配列から削除します。注意すべき重要な点の 1 つは、オブジェクトを使用する場合は常に、オブジェクトへの弱参照を使用する必要があることです。
例えば
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")
}
}
}