Mac Developer Library

Developer

Foundation Framework Reference NSLock Class Reference

Options
Deployment Target:

On This Page
Language:

NSLock

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.

Inheritance


Conforms To


Import Statement


Swift

import Foundation

Objective-C

@import Foundation;

Availability


Available in OS X v10.0 and later.
  • Attempts to acquire a lock before a given time and returns a Boolean value indicating whether the attempt was successful.

    Declaration

    Swift

    func lockBeforeDate(_ limit: NSDate) -> Bool

    Objective-C

    - (BOOL)lockBeforeDate:(NSDate *)limit

    Parameters

    limit

    The time limit for attempting to acquire a lock.

    Return Value

    YEStrue if the lock is acquired before limit, otherwise NOfalse.

    Discussion

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

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.0 and later.

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

    Declaration

    Swift

    func tryLock() -> Bool

    Objective-C

    - (BOOL)tryLock

    Return Value

    YEStrue if the lock was acquired, otherwise NOfalse.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.0 and later.

  • name name Property

    The name associated with the receiver.

    Declaration

    Swift

    var name: String?

    Objective-C

    @property(copy) NSString *name

    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.

    Import Statement

    Objective-C

    @import Foundation;

    Swift

    import Foundation

    Availability

    Available in OS X v10.5 and later.