<!--
{
  "availability" : [
    "iOS: 3.0.0 - 8.0.0",
    "iPadOS: 3.0.0 - 8.0.0",
    "macCatalyst: 13.1.0 - 13.1.0",
    "macOS: 10.4.0 - 10.10.0",
    "visionOS: 1.0.0 - 1.0.0"
  ],
  "documentType" : "symbol",
  "framework" : "CoreData",
  "identifier" : "/documentation/CoreData/NSManagedObjectContext/lock()",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "Core Data"
    ],
    "preciseIdentifier" : "c:objc(cs)NSManagedObjectContext(im)lock"
  },
  "title" : "lock()"
}
-->

# lock()

Attempts to acquire a lock on the context.

```
func lock()
```

## Discussion

This method blocks a thread’s execution until the lock can be acquired. An application protects a critical section of code by requiring a thread to acquire a lock before executing the code. Once the critical section is past, the thread relinquishes the lock by invoking [`unlock()`](/documentation/CoreData/NSManagedObjectContext/unlock()).

Sending this message to a managed object context helps the framework to understand the scope of a transaction in a multi-threaded environment. It is preferable to use the `NSManagedObjectContext`’s implementation of `NSLocking` instead using of a separate mutex object.

If you lock (or successfully `tryLock`) a managed object context, the thread in which the lock call is made must keep a strong reference to the context until it invokes unlock, otherwise if the context is deallocated this will result in deadlock.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)