skip to content

In Core Data, why does a non-optional String attribute generate a String? property, while an optional Integer 16 attribute generates a plain Int16?

level: middleimportance: must knowfreq 58%

answer

  1. two meanings of optional
  2. checked when the context saves
  3. objects can be nil before save
  4. a scalar has no nil
  5. error 1570, the required value

basics

~20 s

Core Data's Optional box is a save-time validation rule, not the Swift type. Object attributes generate Swift optionals because they can be nil before save; scalars generate plain numbers, so an unset optional Int16 reads 0.

solid answer

~40 s

Core Data's **Optional** flag means "may be nil when the context saves": a non-optional attribute left nil makes `save()` throw `NSValidationMissingMandatoryPropertyError` (1570), not the assignment. Because a new object starts nil until you set it, Xcode generates object-typed attributes (`String`, `Date`, `Data`, `UUID`, `URL`, `NSDecimalNumber`) as Swift optionals either way. Numbers and Booleans default to **Use Scalar Type**, generating `Int16`, `Double` or `Bool`, which cannot represent nil, so an unset optional `Int16` reads as `0` while `value(forKey:)` returns nil. To tell "never fertilised" from zero, turn the scalar off and get `NSNumber?`. A model **default value**, such as a watering interval of 7, is applied when the object is inserted.

code

swift · 14 lines
swift
import CoreData

@objc(Plant)
public class Plant: NSManagedObject {}

// Generated by Xcode for the Plant entity (abridged).
extension Plant {
    @NSManaged public var nickname: String?        // String, Optional on
    @NSManaged public var speciesName: String?     // String, Optional off
    @NSManaged public var wateringInterval: Int16  // Integer 16, scalar, default 7
    @NSManaged public var fertiliserDose: Double   // Double, scalar, Optional on
    @NSManaged public var lastWatered: Date?       // Date, scalar off
    @NSManaged public var photo: Data?             // Binary Data, external storage
}

go deeper

for a junior

Recall that the model's Optional box is checked when the context saves, and that a missing required value fails the save with a validation error.

for a middle

Explain how the attribute type and Use Scalar Type choose the generated Swift type, and why an unset optional scalar reads as zero.

for a senior

Spot data bugs where zero and missing were conflated, and choose defaults or NSNumber? before release so the fix needs no migration.

for a principal

Set a team rule for attribute review: types, optionality and defaults are schema decisions that cost a migration to change later.

## Two different meanings of optional In a Core Data model every attribute has an **Optional** box (`isOptional` on `NSPropertyDescription`, `true` by default in code). The header describes it as whether the value "can be nil or not (before an object can be persisted)". It is a **validation rule checked at save**, not a type. A non-optional `speciesName` can be nil all the way from `Plant(context:)` to the save; only then does `save()` throw an `NSError` in `NSCocoaErrorDomain` with code `NSValidationMissingMandatoryPropertyError` (1570), whose message calls the property "a required value". Swift's optional, by contrast, is a compile-time promise about every read. Because a fresh managed object really does hold nil in its non-optional attributes until you set them, Xcode cannot honestly generate `String` for them, and emits `String?`. ## How the generated Swift type is chosen The generated property type depends on the **attribute type** and its **Use Scalar Type** box, not on Optional: | Attribute type | Scalar type | Scalar by default | Without scalar | |---|---|---|---| | Integer 16 / 32 / 64 | `Int16` / `Int32` / `Int64` | yes | `NSNumber?` | | Double, Float | `Double`, `Float` | yes | `NSNumber?` | | Boolean | `Bool` | yes | `NSNumber?` | | Date | `TimeInterval` | no | `Date?` | | String, Binary Data, URI | none | n/a | `String?`, `Data?`, `URL?` | | Decimal, UUID | same class, no separate scalar | no | `NSDecimalNumber?`, `UUID?` | | Transformable | none | n/a | the custom class, or `NSObject?` | A scalar cannot be nil, so: - an **optional scalar** that was never set reads as `0` (or `false`) through the generated property, while `value(forKey:)` still returns nil; - "never fertilised" and "fertilised with 0 ml" become indistinguishable through `fertiliserDose: Double`; - the fix is to clear Use Scalar Type for that attribute and work with `NSNumber?`, or to make the attribute non-optional with a meaningful default. ## Default values An attribute's **default value** (`defaultValue` in code) is applied when the object is inserted, so a new `Plant` reads `wateringInterval == 7` before any code touches it. Two details matter: 1. The model **retains** a default value object rather than copying it, so never mutate an object after setting it as a default. 2. A default makes a non-optional scalar safe to leave untouched, which is usually better than an optional scalar that silently reads 0. 3. A default is part of the model, not of the stored rows: setting a new default value for an attribute leaves existing stores openable, while adding the attribute itself does not, as the model documentation notes. ## The plant-care Plant entity - `nickname`: String, Optional on, so `String?` and nil is a legal saved state. - `speciesName`: String, Optional off, still `String?` in Swift; a nil value fails the save with 1570. - `wateringInterval`: Integer 16, scalar, non-optional, default 7, so `Int16`. - `fertiliserDose`: Double, Optional on, scalar on, so `Double` that reads 0 when unset; switch the scalar off if nil must stay visible. - `lastWatered`: Date with the scalar off, so `Date?`; the scalar form would be a `TimeInterval`. - `photo`: Binary Data with **Allows External Storage** (`allowsExternalBinaryDataStorage`), which lets Core Data keep a large value in a file outside the store while the property is still `Data?`. ## Why the choice comes back later The type and optionality of an attribute describe the store's schema, and the Optional flag is one of the values that make up a property's version hash. Changing an attribute's type, or its optionality, after release changes the schema the store was created with, so the store needs a migration, a subject covered with model versioning and migration. Choosing the type carefully the first time (Integer 16 is enough for a day count, Integer 64 is not needed) saves that work. If the generated `String?` is unwelcome, Manual/None codegen lets you declare `@NSManaged var speciesName: String` yourself; that only changes the Swift surface, and the value can still be nil until it is set.

  • In Core Data, when exactly does a missing non-optional attribute produce an error?
    When the context validates the object during `save()`. Assigning nil, inserting an object without setting the attribute, and fetching are all allowed; the save throws `NSValidationMissingMandatoryPropertyError` (1570), and `validateForInsert()` lets you run the same check earlier.
  • When should a Core Data Binary Data attribute use Allows External Storage?
    For large values such as a plant photo. With `allowsExternalBinaryDataStorage` set, Core Data may keep the bytes in a file outside the persistent store itself, so the store stays small; the attribute's Swift type is still `Data?`.
  • How do you keep nil visible for an optional Core Data number such as a fertiliser dose?
    Clear Use Scalar Type for that attribute so Xcode generates `NSNumber?`, or read it with `value(forKey:)`. With the scalar on, the generated `Double` reports 0 for a value that was never set.

  • Treating the model's Optional box as the same thing as a Swift optional
  • Expecting assigning nil to a non-optional attribute to throw immediately
  • Using an optional scalar and reading 0 as a real recorded value
  • Assuming a non-optional String attribute generates a non-optional String property
  • Changing an attribute's type after release without planning a migration