核心数据 - 监视更改并注册本地通知

Bil*_*iff 5 iphone cocoa-touch core-data key-value-observing

我对Core Data和KVC比较陌生,但是我想要一些关于注册Core Data对象更改的指针.情况如下:

我有一个NSManagedObjectPatient,另一个叫Medication.A Patient可能有很多Medications,而且Medication有一个startOnendOn日期.

我想以某种方式监听endOn所有Medication对象属性的更改.发生更改时,我想在iOS设备上安排本地通知.我之前使用过本地通知,但不知道在这种情况下将代码放在何处.

我是否在App Delegate中创建调度代码并以某种方式注册App Delegate以侦听Medication对象中的更改?这需要附加到NSManagedObjectContext

这是怎么做到的?指针将非常感谢!

谢谢!

wes*_*der 7

使用键值观察,您需要一些实例来进行观察.有时,这可能是调用-setEndOn:on Medication的同一个对象; 有时它可能必须是别的东西.假设您的应用程序有一个MedicationManager类 - 其中一个实例已创建.并且,进一步假设MedicationManager有一个实例方法-createMedicationWithName:startOn:endOn:像这样:

- (Medication*) createMedicationWithName:(NSString*)medName startOn:(NSDate*)startDate endOn:(NSDate*)endDate
    {
    //  Create and configure a new instance of the Compound entity 
    Medication *newMedication = (Medication *)[NSEntityDescription insertNewObjectForEntityForName:@"Medication"
                                                inManagedObjectContext:[self managedObjectContext]];
    [newMedication setName:medName];
    [newMedication setStartOn:startDate];
    [newMedication setEndOn:endDate];

    //  Set up KVO
    [newMedication addObserver:self
                    forKeyPath:@"endOn"
                    options:NSKeyValueObservingOptionNew
                    context:nil];

    return newCompound;
    }


- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object 
                                                    change:(NSDictionary *)change 
                                                    context:(void *)context
    {
    if ([keyPath isEqualToString:@"endOn"])
        {
        //  ... schedule local notification on the iOS device for (Medication*)object.
        return;
        }
    }
Run Code Online (Sandbox Code Playgroud)

或类似的东西.

请注意,当您删除Medication时,您可能希望removeObserver ...此外,在启动应用程序时,您需要将MedicationManager建立为现有药物的观察者.我认为这可以像迭代所有药物并为每个药物调用addObserver一样简单.如果您有许多药物,那么您可能希望以更"懒惰"的方式(即in -awakeFromFetch)执行此操作.