---
title: lock()
framework: coredata
role: symbol
role_heading: Instance Method
path: coredata/nsmanagedobjectcontext/lock()
---

# lock()

Attempts to acquire a lock on the context.

## Declaration

```swift
func lock()
```

## Discussion

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(). 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.

## See Also

### Deprecated instance methods

- [init(concurrencyType:)](coredata/nsmanagedobjectcontext/init(concurrencytype:).md)
- [init()](coredata/nsmanagedobjectcontext/init().md)
- [tryLock()](coredata/nsmanagedobjectcontext/trylock().md)
- [unlock()](coredata/nsmanagedobjectcontext/unlock().md)
