<!--
{
  "availability" : [
    "iOS: 3.0.0 -",
    "iPadOS: 3.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.4.0 -",
    "tvOS: -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "CoreData",
  "identifier" : "/documentation/CoreData/NSManagedObject",
  "metadataVersion" : "0.1.0",
  "role" : "Class",
  "symbol" : {
    "kind" : "Class",
    "modules" : [
      "Core Data"
    ],
    "preciseIdentifier" : "c:objc(cs)NSManagedObject"
  },
  "title" : "NSManagedObject"
}
-->

# NSManagedObject

The base class that all Core Data model objects inherit from.

```
nonisolated class NSManagedObject
```

## Overview

A managed object has an associated entity description ([`NSEntityDescription`](/documentation/CoreData/NSEntityDescription)) that provides metadata about the object, including the name of the entity that the object represents and the names of its attributes and relationships. A managed object also has an associated managed object context that tracks changes to the object graph.

You can’t use instances of direct subclasses of <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class>, or any other class that doesn’t inherit from [`NSManagedObject`](/documentation/CoreData/NSManagedObject), with a managed object context. You may create custom subclasses of [`NSManagedObject`](/documentation/CoreData/NSManagedObject), although this isn’t always necessary. If you don’t need custom logic, you can create a complete object graph with [`NSManagedObject`](/documentation/CoreData/NSManagedObject) instances.

If you instantiate a managed object directly, you must call the designated initializer [`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:)).

### Data Storage

In some respects, an `NSManagedObject` acts like a dictionary—it’s a generic container object that provides efficient storage for the properties defined by its associated `NSEntityDescription` instance. `NSManagedObject` supports a range of common types for attribute values, including string, date, and number (see [`NSAttributeDescription`](/documentation/CoreData/NSAttributeDescription) for full details). Therefore, typically you don’t need to define instance variables in subclasses. Sometimes, however, you want to use types that aren’t supported directly, such as colors and C structures. For example, in a graphics application you might want to define a Rectangle entity that has color and bounds attributes that are an instance of `NSColor` and an `NSRect` struct, respectively. For some types you can use a transformable attribute, for others this may require you to create a subclass of `NSManagedObject`.

> Note: The default value for <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/automaticallyNotifiesObservers(forKey:)> is `false` for managed properties of a `NSManagedObject`, and `true` for unmanaged properties.

### Faulting

Managed objects typically represent data held in a persistent store. In some situations a managed object may be a *fault*—an object whose property values haven’t yet been loaded from the external data store. When you access persistent property values, the fault “fires” and the data is retrieved from the store automatically. This can be a comparatively expensive process (potentially requiring a round trip to the persistent store), and you may wish to avoid unnecessarily firing a fault. See [Faulting and Uniquing](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/FaultingandUniquing.html#//apple_ref/doc/uid/TP40001075-CH18) for more details on faults.

You can safely invoke the following methods and properties on a fault without causing it to fire: <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isEqual(_:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/hash>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/superclass>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-c.protocol/class>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/self()>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isProxy()>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isKind(of:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isMember(of:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/conforms(to:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/responds(to:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/description>, [`managedObjectContext`](/documentation/CoreData/NSManagedObject/managedObjectContext), [`entity`](/documentation/CoreData/NSManagedObject/entity-swift.property), [`objectID`](/documentation/CoreData/NSManagedObject/objectID), [`isInserted`](/documentation/CoreData/NSManagedObject/isInserted), [`isUpdated`](/documentation/CoreData/NSManagedObject/isUpdated), [`isDeleted`](/documentation/CoreData/NSManagedObject/isDeleted), [`faultingState`](/documentation/CoreData/NSManagedObject/faultingState), and [`isFault`](/documentation/CoreData/NSManagedObject/isFault). Because `isEqual` and `hash` don’t cause a fault to fire, managed objects can typically be placed in collections without firing a fault. Note, however, that invoking key-value coding methods on the collection object might in turn result in an invocation of `valueForKey:` on a managed object, which would fire the fault.

Although the `description` property doesn’t cause a fault to fire, if you implement a custom `description` that accesses the object’s persistent properties, this does cause a fault to fire. You are strongly discouraged from overriding `description` in this way.

### Subclassing Notes

In combination with the entity description in the managed object model, `NSManagedObject` provides a rich set of default behaviors including support for arbitrary properties and value validation. If you decide to subclass `NSManagedObject` to implement custom features, make sure you don’t disrupt Core Data’s behavior.

#### Methods and Properties You Must Not Override

`NSManagedObject` itself customizes many features of `NSObject` so that managed objects can be properly integrated into the Core Data infrastructure. Core Data relies on the `NSManagedObject` implementation of the following methods and properties, which you therefore absolutely must not override: [`primitiveValue(forKey:)`](/documentation/CoreData/NSManagedObject/primitiveValue(forKey:)), [`setPrimitiveValue(_:forKey:)`](/documentation/CoreData/NSManagedObject/setPrimitiveValue(_:forKey:)), <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isEqual(_:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/hash>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/superclass>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-c.protocol/class>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/self()>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isProxy()>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isKind(of:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/isMember(of:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/conforms(to:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObjectProtocol/responds(to:)>, [`managedObjectContext`](/documentation/CoreData/NSManagedObject/managedObjectContext), [`entity`](/documentation/CoreData/NSManagedObject/entity-swift.property), [`objectID`](/documentation/CoreData/NSManagedObject/objectID), [`isInserted`](/documentation/CoreData/NSManagedObject/isInserted), [`isUpdated`](/documentation/CoreData/NSManagedObject/isUpdated), [`isDeleted`](/documentation/CoreData/NSManagedObject/isDeleted), and [`isFault`](/documentation/CoreData/NSManagedObject/isFault), <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/alloc>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/allocWithZone:>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/new>,  <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/instancesRespond(to:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/instanceMethod(for:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/method(for:)>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/methodSignatureForSelector:>, <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/instanceMethodSignatureForSelector:>, or <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/isSubclass(of:)>.

#### Methods and Properties You Shouldn’t Override

As with any class, you are strongly discouraged from overriding the key-value observing methods such as <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/willChangeValue(forKey:)> and <doc://com.apple.documentation/documentation/ObjectiveC/NSObject-swift.class/didChangeValue(forKey:withSetMutation:using:)>. Avoid overriding `description`—if this method fires a fault during a debugging operation, the results may be unpredictable. Also avoid overriding [`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:)), or `dealloc`. Changing values in the [`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:)) method won’t be noticed by the context, and if you aren’t careful, those changes may not be saved. Perform most initialization customization in one of the `awake…` methods. If you do override [`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:)), make sure you adhere to the requirements set out in the method description. See [`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:)).

Don’t override `dealloc` because [`didTurnIntoFault()`](/documentation/CoreData/NSManagedObject/didTurnIntoFault()) is usually a better time to clear values—a managed object may not be reclaimed for some time after it has been turned into a fault. Core Data doesn’t guarantee that `dealloc` will be called in all scenarios (such as when the application quits). Therefore, don’t include required side effects (like saving or changes to the file system, user preferences, and so on) in these methods.

In summary, for [`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:)) and `dealloc`, Core Data reserves exclusive control over the life cycle of the managed object (that is, raw memory management). This is so that the framework can provide features such as uniquing and by consequence, relationship maintenance, as well as much better performance than would be possible otherwise.

#### Additional Override Considerations

The following methods are intended to be fine grained and aren’t suitable for large-scale operations. Don’t fetch or save in these methods. In particular, they shouldn’t have side effects on the managed object context.

- [`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:))
- [`didTurnIntoFault()`](/documentation/CoreData/NSManagedObject/didTurnIntoFault())
- [`willTurnIntoFault()`](/documentation/CoreData/NSManagedObject/willTurnIntoFault())
- `dealloc`

In addition, if you plan to override `awakeFromInsert`, `awakeFromFetch`, and validation methods, first invoke `super.method()`, the superclass’s implementation. Don’t modify relationships in [`awakeFromFetch()`](/documentation/CoreData/NSManagedObject/awakeFromFetch())—see the method description for details.

#### Custom Accessor Methods

Typically, you don’t need to write custom accessor methods for properties that are defined in the entity of a managed object’s corresponding managed object model. If you need to do so, follow the implementation patterns described in Managed Object Accessor Methods in [Core Data Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html#//apple_ref/doc/uid/TP40001075).

Core Data automatically generates accessor methods (and primitive accessor methods) for you. For attributes and to-one relationships, Core Data generates the standard get and set accessor methods; for to-many relationships, Core Data generates the indexed accessor methods as described in [Achieving Basic Key-Value Coding Compliance](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/AccessorConventions.html#//apple_ref/doc/uid/20002174) in [Key-Value Coding Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/KeyValueCoding/index.html#//apple_ref/doc/uid/10000107i). You do however need to declare the accessor methods or use Objective-C properties to suppress compiler warnings. For a full discussion, see Managed Object Accessor Methods in [Core Data Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html#//apple_ref/doc/uid/TP40001075).

#### Custom Instance Variables

By default, `NSManagedObject` stores its properties in an internal structure as objects, and in general Core Data is more efficient working with storage under its own control rather than by using custom instance variables.

`NSManagedObject` provides support for a range of common types for attribute values, including string, date, and number (see [`NSAttributeDescription`](/documentation/CoreData/NSAttributeDescription) for full details). If you want to use types that aren’t supported directly, like colors and C structures, you can either use transformable attributes or create a subclass of `NSManagedObject`.

Sometimes it’s convenient to represent variables as scalars—in drawing applications, for example, where variables represent dimensions and x and y coordinates and are frequently used in calculations. To represent attributes as scalars, you declare instance variables as you do in any other class. You also need to implement suitable accessor methods as described in Managed Object Accessor Methods.

If you define custom instance variables for example to store derived attributes or other transient properties, clean up these variables in [`didTurnIntoFault()`](/documentation/CoreData/NSManagedObject/didTurnIntoFault()) rather than `dealloc`.

#### Validation Methods

`NSManagedObject` provides consistent hooks for validating property and inter-property values. You typically shouldn’t override [`validateValue(_:forKey:)`](/documentation/CoreData/NSManagedObject/validateValue(_:forKey:)). Instead implement methods of the form `validate<Key>:error:`, as defined by the NSKeyValueCoding protocol. If you want to validate inter-property values, you can override [`validateForUpdate()`](/documentation/CoreData/NSManagedObject/validateForUpdate()) and/or related validation methods.

Don’t call `validateValue:forKey:error:` within custom property validation methods—if you do, you create an infinite loop when `validateValue:forKey:error:` is invoked at runtime. If you do implement custom validation methods, don’t call them directly. Instead, call `validateValue:forKey:error:` with the appropriate key. This ensures that any constraints defined in the managed object model are applied.

If you implement custom inter-property validation methods like [`validateForUpdate()`](/documentation/CoreData/NSManagedObject/validateForUpdate()), call the superclass’s implementation first. This ensures that individual property validation methods are also invoked. If there are multiple validation failures in one operation, collect them in an array and add the array—using the key `NSDetailedErrorsKey`—to the userInfo dictionary in the `NSError` object you return. For an example, see Managed Object Validation.

## Topics

### Creating a Managed Object

[`init(entity:insertInto:)`](/documentation/CoreData/NSManagedObject/init(entity:insertInto:))

Initializes a managed object from an entity description and inserts it into the specified managed object context.

[`init(context:)`](/documentation/CoreData/NSManagedObject/init(context:))

Initializes a managed object subclass and inserts it into the specified managed object context.

### Getting a Managed Object’s Identity

[`entity`](/documentation/CoreData/NSManagedObject/entity-swift.property)

The entity description of the managed object.

[`objectID`](/documentation/CoreData/NSManagedObject/objectID)

The object ID of the managed object.

[`entity()`](/documentation/CoreData/NSManagedObject/entity())

Returns the entity description that is associated with this subclass.

### Getting State Information

[`managedObjectContext`](/documentation/CoreData/NSManagedObject/managedObjectContext)

The managed object context with which the managed object is registered.

[`hasChanges`](/documentation/CoreData/NSManagedObject/hasChanges)

A Boolean value that indicates whether the managed object has been inserted, has been deleted, or has unsaved changes.

[`isInserted`](/documentation/CoreData/NSManagedObject/isInserted)

A Boolean value that indicates whether the managed object has been inserted in a managed object context.

[`isUpdated`](/documentation/CoreData/NSManagedObject/isUpdated)

A Boolean value that indicates whether the managed object has unsaved changes.

[`isDeleted`](/documentation/CoreData/NSManagedObject/isDeleted)

A Boolean value that indicates whether the managed object will be deleted during the next save.

[`isFault`](/documentation/CoreData/NSManagedObject/isFault)

A Boolean value that indicates whether the managed object is a fault.

[`faultingState`](/documentation/CoreData/NSManagedObject/faultingState)

The faulting state of the managed object.

[`hasFault(forRelationshipNamed:)`](/documentation/CoreData/NSManagedObject/hasFault(forRelationshipNamed:))

Returns a Boolean value that indicates whether the relationship for a given key is a fault.

[`hasPersistentChangedValues`](/documentation/CoreData/NSManagedObject/hasPersistentChangedValues)

A Boolean value that indicates whether the managed object has persistent changes.

### Managing Change Events

[`contextShouldIgnoreUnmodeledPropertyChanges`](/documentation/CoreData/NSManagedObject/contextShouldIgnoreUnmodeledPropertyChanges)

A Boolean value that indicates whether to mark instances of the class as having changes when an unmodeled property changes.

[`awakeFromFetch()`](/documentation/CoreData/NSManagedObject/awakeFromFetch())

Provides an opportunity to add code into the life cycle of the managed object when fufilling it from a fault.

[`awakeFromInsert()`](/documentation/CoreData/NSManagedObject/awakeFromInsert())

Provides an opportunity to add code into the life cycle of the managed object when initially creating it.

[`awake(fromSnapshotEvents:)`](/documentation/CoreData/NSManagedObject/awake(fromSnapshotEvents:))

Provides an opportunity to add code into the life cycle of the managed object when fulfilling it from a snapshot.

[`changedValues()`](/documentation/CoreData/NSManagedObject/changedValues())

Returns a dictionary containing the keys and new values of persistent properties with changes since the last fetching or saving of the managed object.

[`changedValuesForCurrentEvent()`](/documentation/CoreData/NSManagedObject/changedValuesForCurrentEvent())

Returns a dictionary containing the keys and new values of persistent properties with changes since the last fetching or saving of the managed object.

[`committedValues(forKeys:)`](/documentation/CoreData/NSManagedObject/committedValues(forKeys:))

Returns a dictionary of the most recent fetched or saved values of the managed object for the properties of the specified keys.

[`prepareForDeletion()`](/documentation/CoreData/NSManagedObject/prepareForDeletion())

Provides an opportunity to add code into the life cycle of the managed object before deleting it.

[`willSave()`](/documentation/CoreData/NSManagedObject/willSave())

Provides an opportunity to add code into the life cycle of the managed object before saving it.

[`didSave()`](/documentation/CoreData/NSManagedObject/didSave())

Provides an opportunity to add code into the life cycle of the managed object after the managed object’s context completes a save operation.

[`willTurnIntoFault()`](/documentation/CoreData/NSManagedObject/willTurnIntoFault())

Provides an opportunity to add code into the life cycle of the managed object before converting it to a fault.

[`didTurnIntoFault()`](/documentation/CoreData/NSManagedObject/didTurnIntoFault())

Provides an opportunity to add code into the life cycle of the managed object after converting it to a fault.

[`fetchRequest()`](/documentation/CoreData/NSManagedObject/fetchRequest())

Returns an initialized fetch request with the entity this subclass represents.

[`fetchRequest`](/documentation/CoreData/NSManagedObject/fetchRequest)

Returns an initialized fetch request with the entity this subclass represents.

### Supporting Key-Value Coding

[`value(forKey:)`](/documentation/CoreData/NSManagedObject/value(forKey:))

Returns the value for the property specified by `key`.

[`setValue(_:forKey:)`](/documentation/CoreData/NSManagedObject/setValue(_:forKey:))

Sets the specified property of the managed object to the specified value.

[`primitiveValue(forKey:)`](/documentation/CoreData/NSManagedObject/primitiveValue(forKey:))

Returns the value for the specified property from the managed object’s private internal storage .

[`setPrimitiveValue(_:forKey:)`](/documentation/CoreData/NSManagedObject/setPrimitiveValue(_:forKey:))

Sets the value of a given property in the managed object’s private internal storage.

[`objectIDs(forRelationshipNamed:)`](/documentation/CoreData/NSManagedObject/objectIDs(forRelationshipNamed:))

Returns the object IDs for all of the managed objects that are in the named relationship.

### Managing Data Validation

[`validateValue(_:forKey:)`](/documentation/CoreData/NSManagedObject/validateValue(_:forKey:))

Validates a property value for a given key.

[`validateForDelete()`](/documentation/CoreData/NSManagedObject/validateForDelete())

Determines whether the managed object can be deleted in its current state.

[`validateForInsert()`](/documentation/CoreData/NSManagedObject/validateForInsert())

Determines whether the managed object can be inserted in its current state.

[`validateForUpdate()`](/documentation/CoreData/NSManagedObject/validateForUpdate())

Determines whether the managed object’s current state is valid.

[Validation error codes](/documentation/CoreData/1535452-validation-error-codes)

Error codes relating to the validation of managed objects.

[`NSValidationKeyErrorKey`](/documentation/CoreData/NSValidationKeyErrorKey)

The error key for the attribute that failed to validate.

[`NSValidationObjectErrorKey`](/documentation/CoreData/NSValidationObjectErrorKey)

The error key for the object that failed to validate.

[`NSValidationPredicateErrorKey`](/documentation/CoreData/NSValidationPredicateErrorKey)

The error key for the predicate that failed to validate.

[`NSValidationValueErrorKey`](/documentation/CoreData/NSValidationValueErrorKey)

The error key for the value that failed to validate.

### Supporting Key-Value Observing

[`didAccessValue(forKey:)`](/documentation/CoreData/NSManagedObject/didAccessValue(forKey:))

Provides support for key-value observing access notification.

[`observationInfo()`](/documentation/CoreData/NSManagedObject/observationInfo())

Returns the observation info of the managed object.

[`setObservationInfo(_:)`](/documentation/CoreData/NSManagedObject/setObservationInfo(_:))

Sets the observation info of the managed object.

[`willAccessValue(forKey:)`](/documentation/CoreData/NSManagedObject/willAccessValue(forKey:))

Provides support for key-value observing access notification.

[`didChangeValue(forKey:)`](/documentation/CoreData/NSManagedObject/didChangeValue(forKey:))

Provides an opportunity to respond when a value of a given property has changed.

[`didChangeValue(forKey:withSetMutation:using:)`](/documentation/CoreData/NSManagedObject/didChangeValue(forKey:withSetMutation:using:))

Provides an opportunity to respond when a change was made to a specified to-many relationship.

[`willChangeValue(forKey:)`](/documentation/CoreData/NSManagedObject/willChangeValue(forKey:))

Provides an opportunity to respond when a value of a given property is about to change.

[`willChangeValue(forKey:withSetMutation:using:)`](/documentation/CoreData/NSManagedObject/willChangeValue(forKey:withSetMutation:using:))

Provides an opportunity to respond when a change is about to be made to a specified to-many relationship.

### Reinitializing Values

[`NSSnapshotEventType`](/documentation/CoreData/NSSnapshotEventType)

Constants that specify the reason the managed object may need to reinitialize its values.



---

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)