我有一个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"];
}
}
这是观察依赖关系的核心数据属性的正确/无错误/首选方式还是我滥用框架?