Cocoa threading question.

Posted by Steve918 on Stack Overflow See other posts from Stack Overflow or by Steve918
Published on 2010-03-20T18:25:15Z Indexed on 2010/03/20 18:31 UTC
Read the original article Hit count: 574

I would like to implement an observer pattern in Objective-C where the observer implements an interface similar to SKPaymentTransactionObserver and the observable class just extends my base observable. My observable class looks something like what is below. Notice I'm making copies of the observers before enumeration to avoid throwing an exception .

I've tried adding an NSLock around add observers and notify observers, but I run into a deadlock.

What would be the proper way to handle concurrency when observers are being added as notifications are being sent?

@implementation Observable

-(void)notifyObservers:(SEL)selector {
    @synchronized(self) {
        NSSet* observer_copy = [observers copy];
        for (id observer in observer_copy) {
            if([observer respondsToSelector: selector]) {
                [observer performSelector: selector];
            }
        }
        [observer_copy release];
    }
}

-(void)notifyObservers:(SEL)selector withObject:(id)arg1 withObject:(id)arg2 {
    @synchronized(self) {
 NSSet* observer_copy = [observers copy];
        for (id observer in observer_copy) {
            if([observer respondsToSelector: selector]) {
                [observer performSelector: selector withObject: arg1 withObject: arg2];
            }
        }
       [observer_copy release];
    }
}

-(void)addObserver:(id)observer {
    @synchronized(self) {
        [observers addObject: observer];
    }
}

-(void)removeObserver:(id)observer {
    @synchronized(self) {
       [observers removeObject: observer];
    }
}

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about cocoa