Junior — Middle
Can you explain what the NSLock class is used for in Objective-C development?
sobes.tech AI
Answer from AI
The NSLock class in Objective-C is used to implement mutual exclusion (mutex), that is, to synchronize access to shared resources between threads. This prevents race conditions when multiple threads try to modify the same data simultaneously.
Example of using NSLock:
NSLock *lock = [[NSLock alloc] init];
// In one of the threads
[lock lock];
// Critical section: safe access to shared resource
// ...
[lock unlock];
NSLock blocks the thread when lock is called if another thread already holds the lock, and releases it when unlock is called. It is a simple and effective way to ensure thread safety in multi-threaded applications on iOS/macOS.