Will this RAII-style Objective-C class work?

Better API: use a block:

void performBlockWithLock(NSLock *lock, void (^block)(void)) {
    [lock lock];
    block();
    [lock unlock];
}

Example:

NSLock *someLock = ...;
performBlockWithLock(someLock, ^{
    // your code here
});

If you want RAII patterns, you should use Objective-C++ and write C++ RAII classes.

ARC is unlikely to give you the result you want. The object may be deallocated too late, if something causes it to be autoreleased. The object may be deallocated too early, if the ARC optimizer decides the object is no longer used.


I would say that class methods like

+ (Locker *)lockerWithLock:(NSLock *)lock;

would probably cause ARC to autorelease the return value (see this article). I think it will be autoreleased unless the method name begins with alloc, new, init, copy, mutableCopy (or unless you use special macros to force the compiler into not autoreleasing, NS_RETURNS_RETAINED), the clang ARC documentation is pretty good. An autoreleased object would obviously be a problem given your lock wouldn't be unlocked until the autorelease pool is drained.

I always thought of RAII as being a C/C++ thing where you can allocate objects statically. But I guess you can do it this way, as long as you make well sure that the objects are not autoreleased.