Unable to subclass NSManagedObject

Xcode 6 has a ton of bugs. But I'm not quite sure if this is a mistake or not. Perhaps this is not so, because that is what I am currently studying.

My problem is that whenever I try to instantiate my subclass of NSManagedObject, I have no way to pass the entity: NSEntityDescription argument entity: NSEntityDescription and NSManagedContext: insertIntoManagedContext constructor, Xcode says "object" Extra argument "in the call" <

I created a new Xcode project from scratch, just to see if I can recreate the problem in a smaller minimal project.

ToDoList.Item is set as the Item entity class in the data model inspector.

Here is the code:

 override func viewDidLoad() { super.viewDidLoad() let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate let context: NSManagedObjectContext = appDel.managedObjectContext! let ent = NSEntityDescription.entityForName("Item", inManagedObjectContext: context)! //compiler complains here var item = Item(entity: ent, insertIntoManagedObjectContext: context)! } 

Here's the subclass:

 import UIKit import CoreData class Item: NSManagedObject { @NSManaged var title: String @NSManaged var completed: Bool } 

All help is appreciated.

+6
source share
3 answers

Just stumbled upon the same problem: Init method is not available for the main data object

Obviously we need to implement

 init(entity: NSEntityDescription, insertIntoManagedObjectContext context, NSManagedObjectContext?) 

in our usual NSManagedObject class. Therefore just add

 override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } 

for your entity class, and it will work.

+5
source

Try the last line without an exclamation mark, for example:

 var item = Item(entity: ent, insertIntoManagedObjectContext: context) 

And you may not have added your application name to the class name:

Swift classes are namespaced-theyre tied to the module (usually the project) in which they are compiled. To use the Swift subclass of NSManagedObject with the Core Data model, prefix the class name in the Class field in the object inspector model with the name of your module.

Class name https://developer.apple.com/library/mac/documentation/Swift/Conceptual/BuildingCocoaApps/WritingSwiftClassesWithObjective-CBehavior.html

+1
source

Are constructors inherited in Swift?

I would try using NSEntityDescription.insertNewObjectForEntityForName: inManagedObjectContext

0
source

Source: https://habr.com/ru/post/977312/


All Articles