ios學習--KVO模式關鍵函數

將self添加爲self.inProgressAdder的觀察者,觀察的屬性爲 isFinished,isExecuting


- (void)addObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath options:(NSKeyValueObservingOptions)options context:(void *)context;

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;

以上兩個函數放在self這個的實現中

[self.inProgressAdder addObserver:self forKeyPath:@"isFinished"  options:0 context:&self->_formattedTotal];
[self.inProgressAdder addObserver:self forKeyPath:@"isExecuting" options:0 context:&self->_queue];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (context == &self->_formattedTotal) {
        AdderOperation *    op;

        // If the operation has finished, call -adderOperationDone: on the main thread to deal
        // with the results.

        // can be running on any thread
        assert([keyPath isEqual:@"isFinished"]);
        op = (AdderOperation *) object;
        assert([op isKindOfClass:[AdderOperation class]]);
        assert([op isFinished]);

        fprintf(stderr, "%c %3lu finished\n", CharForCurrentThread(), (unsigned long) op.sequenceNumber);
        if ([[NSUserDefaults standardUserDefaults] boolForKey:@"applyResultsFromThread"]) {
            [self adderOperationDone:op];
        } else {
            if ([[NSUserDefaults standardUserDefaults] boolForKey:@"allowStale"]) {
                [self performSelectorOnMainThread:@selector(adderOperationDoneWrong:) withObject:op waitUntilDone:NO];
            } else {
                [self performSelectorOnMainThread:@selector(adderOperationDone:)      withObject:op waitUntilDone:NO];
            }
        }
    } else if (context == &self->_queue) {
        AdderOperation *    op;
       
        // We observe -isExecuting purely for logging purposes.
       
        // can be running on any thread
        assert([keyPath isEqual:@"isExecuting"]);
        op = (AdderOperation *) object;
        assert([op isKindOfClass:[AdderOperation class]]);
        if ([op isExecuting]) {
            fprintf(stderr, "%c %3lu executing\n", CharForCurrentThread(), (unsigned long) op.sequenceNumber);
  
發佈了20 篇原創文章 · 獲贊 6 · 訪問量 45萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章