Search code examples
swiftcore-datansmanagedobject

Why can @NSManaged properties be stored in extensions?


How can the @NSManaged properties be in an extension when extensions can't contain stored properties? Why are they not the same as stored properties?

A popular format for core data files is a core data class, and then an extension containing the core data properties.

//User+CoreDataClass
@objc(User)
public class User: NSManagedObject {
  var fullName: String {
    return "\(firstName) \(lastName)" 
  }
}

//User+CoreDataProperties
extension User {
  // Why can these @NSManaged properties live in an extension?
  @NSManaged public var id: Int64
  @NSManaged public var firstName: String
  @NSManaged public var lastName: String

  var storedProp: String // Error: Extensions must not contain stored properties
}

Solution

  • Technically @NSManaged properties are computed properties.

    Core Data synthesizes getter and setter.