领域数据库 - 删除对象时的通知

时间:2016-05-19 09:37:17

标签: ios realm

我的问题很简单:当一个对象的实例即将被删除时,是否有某种方法可以通知它?

我有一个案例,我有一个属性是存储在磁盘上的图像的路径。每当删除该类型的领域对象时,我想删除此图像。

2 个答案:

答案 0 :(得分:2)

您可以使用KVO观察// a global context object to identify our observations let myContext = UnsafePointer<()>() class MyClass { func stuff() { object.addObserver(self, forKeyPath: "invalidated", options: [.Prior], context: myContext) } override func observeValueForKeyPath(keyPath: String!, ofObject object: AnyObject!, change: [NSObject : AnyObject]!, context: UnsafePointer<()>) { if context == myContext && keyPath == "invalidated" { print("\(object) is about to be deleted") object.removeObserver(self, forKeyPath: "invalidated", context: myContext) } else { super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context) } } } 属性:

Sub Button2_Click()
    numRows = 10 ' Number fo rows to loop through, in your case 5000

    'loop through each cell located in column 1
    'Check its type
    'Concatenate each one in 1 cell on the 8th column
    For i = 1 To numRows
        Sheet1.Cells(1, 8).Value = Sheet1.Cells(1, 8).Value & TypeName(Sheet1.Cells(i, 1).Value) & ","
    Next i
End Sub

您可能希望使用PMKVObserverKVOController之类的内容来简化此操作,因为直接使用KVO可能会让您感到不快。

答案 1 :(得分:1)

如果您不想使用KVO,可以利用Realm的Object Notifications

一个简短的例子是:

public static class AlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //execute my task
        Toast.makeText(context, " hello", Toast.LENGTH_SHORT).show();
    }
}

只需确保保留对令牌对象的强引用,因为Realm一释放就会自动取消订阅通知块。