NSLock Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/Foundation.framework
Availability
Available in OS X v10.0 and later.
Companion guide
Declared in
NSLock.h
Related sample code

Overview

An NSLock object is used to coordinate the operation of multiple threads of execution within the same application. An NSLock object can be used to mediate access to an application’s global data or to protect a critical section of code, allowing it to run atomically.

You should not use this class to implement a recursive lock. Calling the lock method twice on the same thread will lock up your thread permanently. Use the NSRecursiveLock class to implement recursive locks instead.

Unlocking a lock that is not locked is considered a programmer error and should be fixed in your code. The NSLock class reports such errors by printing an error message to the console when they occur.

Adopted Protocols

NSLocking

Tasks

Acquiring a Lock

Naming the Lock

Instance Methods

lockBeforeDate:

Attempts to acquire a lock before a given time and returns a Boolean value indicating whether the attempt was successful.

- (BOOL)lockBeforeDate:(NSDate *)limit
Parameters
limit

The time limit for attempting to acquire a lock.

Return Value

YES if the lock is acquired before limit, otherwise NO.

Discussion

The thread is blocked until the receiver acquires the lock or limit is reached.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSLock.h

name

Returns the name associated with the receiver.

- (NSString *)name
Return Value

The name of the receiver.

Availability
  • Available in OS X v10.5 and later.
See Also
Declared In
NSLock.h

setName:

Assigns a name to the receiver.

- (void)setName:(NSString *)newName
Parameters
newName

The new name for the receiver. This method makes a copy of the specified string.

Discussion

You can use a name string to identify a lock within your code. Cocoa also uses this name as part of any error descriptions involving the receiver.

Availability
  • Available in OS X v10.5 and later.
See Also
Declared In
NSLock.h

tryLock

Attempts to acquire a lock and immediately returns a Boolean value that indicates whether the attempt was successful.

- (BOOL)tryLock
Return Value

YES if the lock was acquired, otherwise NO.

Availability
  • Available in OS X v10.0 and later.
Declared In
NSLock.h