In C ++, I have a Mutex class, and I use this RAII style class to ensure that the mutex is unlocked, regardless of the reason the method returns:
class MutexLock { protected: Mutex &m_mutex; public: MutexLock(Mutex &mutex) : m_mutex(mutex) { m_mutex.lock(); } ~MutexLock() { m_mutex.unlock(); } };
Is there any reason, and when using ARC, the equivalent Objective-C class will not work:
@interface Locker : NSObject { NSLock *_lock; } - (void)setLock:(NSLock *)lock; @end @implementation Locker - (void)setLock:(NSLock *)lock { [_lock unlock]; _lock = lock; [_lock lock]; } - (void)dealloc { self.lock = nil; } @end
What can be used as follows:
NSLock *_lock;
I understand that this will not work in the case of Objective-C exceptions, unlike the C ++ version, but if all Objective-C exceptions are fatal, I am not worried about that.
UPDATE Just tapped a quick test, and it seems to be working fine. See gist .
c ++ objective-c mutex raii
trojanfoe
source share