我有一个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"];
  }
}


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

最佳答案

latestInvoice注册为invoicesdependent key

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

10-08 02:48