如何发布依赖于关系的自定义Core Data属性的通知?

时间:2012-10-08 18:10:00

标签: ios macos cocoa core-data cocoa-bindings

我的ClientInvoice有很多关系,该属性称为invoices。现在我写了一个自定义的只读属性latestInvoice,我想在我的界面中观察:

- (MyInvoice *)latestInvoice
{
  NSArray *invoices = [self valueForKey:@"invoices"];
  NSSortDescriptor *sortDescriptor = [NSSortDescriptor
    sortDescriptorWithKey:@"date" ascending:NO];

  return invoices.count
    ? [invoices sortedArrayUsingDescriptors:@[sortDescriptor]][0]
    : nil;
}

我注册Client作为invoices的观察员:

- (void)dealloc
{
  [self removeObserver:self forKeyPath:@"invoices"];
}

- (void)registerObservers
{
  [self addObserver:self forKeyPath:@"invoices" options:
    (NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld)
    context:NULL];
}

- (void)awakeFromInsert
{
  [super awakeFromInsert];

  [self registerObservers];
}

- (void)awakeFromFetch
{
  [super awakeFromFetch];

  [self registerObservers];
}

我手动发布更改通知:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
  change:(NSDictionary *)change context:(void *)context
{
  if ([keyPath isEqualToString:@"invoices"])
  {
    [self willChangeValueForKey:@"latestInvoice"];
    [self didChangeValueForKey:@"latestInvoice"];
  }
}

这是正确的/无错误/首选的方法来观察依赖于关系的核心数据属性还是滥用框架?

1 个答案:

答案 0 :(得分:1)

latestInvoice注册为invoices的{​​{3}}。

+ (NSSet *)keyPathsForValuesAffectingLatestInvoice {
    return [NSSet setWithObjects:@"invoices", nil];
}