1

我有一个Client与 具有多对多关系Invoice的属性,称为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"];
  }
}

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

4

1 回答 1

1

注册latestInvoice为 的依赖invoices

+ (NSSet *)keyPathsForValuesAffectingLatestInvoice {
    return [NSSet setWithObjects:@"invoices", nil];
}
于 2012-10-08T18:16:16.447 回答