2012-10-08 53 views
1

我有一個Client,它與Invoice有多對多關係,該屬性被稱爲invoices。現在我寫的,我想在我的接口來觀察一個自定義的只讀屬性latestInvoice如何發佈取決於關係的自定義Core Data屬性的通知?

- (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

註冊latestInvoice作爲dependent keyinvoices

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

我應該把頭撞在牆上。感謝您的準確答案。以下是相應的文檔:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CoreData/Articles/cdFAQ.html#//apple_ref/doc/uid/TP40001802-DontLinkElementID_13 –

+0

您是否驗證過這有用嗎?文檔中有一段指出,具有多對多關係的相關鍵不會起作用。但據我所知,這只是一個問題,當你試圖觀察數組中元素的屬性時,而不是改變數組本身(例如添加新對象,刪除對象)。 – DrummerB

+1

到目前爲止,它對我們的測試版測試人員來說沒有任何問題。讓我們看看發佈後會發生什麼。 –

相關問題