我的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"];
}
}
这是正确的/无错误/首选的方法来观察依赖于关系的核心数据属性还是滥用框架?
答案 0 :(得分:1)
将latestInvoice
注册为invoices
的{{3}}。
+ (NSSet *)keyPathsForValuesAffectingLatestInvoice {
return [NSSet setWithObjects:@"invoices", nil];
}