I keep getting this error whenever I try to update a value of core data model. Here is my model
import Foundation
import CoreData
@objc(Habit)
class Habit:
Ok so the reason you are getting the error is most certainly because the object referenced by self.habit
is not a Habit
object. The easiest way to find out what the object really is is to call:
print(NSStringFromClass(habit.class))
With core data and custom NSManagedObjects
you need to make sure that the entity: 'Habit' (in your data model) has a class set to Habit. This makes sure that Core Data casts your fetched objects with an entity description of 'Habit' to the Habit class. If you are not doing this then the getHabits
func will be returning an array of NSManagedObject
s not an array of Habit
s.If this is the case then the code: println(NSStringFromClass(habit.class))
will print "NSManagedObject" to the debugger.
As a side note, you really need to check for errors when you fetch objects from a Core Data database. Add the lines:
if objects? == nil {
print("An error occurred \error.localisedDescription")
}
Please forgive my swift if there are any errors, I normally use Objective-C.
EDIT: In order to correct Failed to call designated initializer on NSManagedObject class 'X'
error. This error is fired when you do not correctly instantiate an NSManagedObject
. You must not call [[MyManagedObject alloc] init];
you have to call initWithEntity:insertIntoManagedObjectContext
instead:
MyManagedObject *obj = [[MyManagedObject alloc] initWithEntity:[NSEntityDescription entityForName:@"MyManagedObject" inManagedObjectContext:context] insertIntoManagedObjectContext:context];
If you do not want the object obj
to be inserted into a context you can pass through a nil
context argument. However, if you want undo management and the ability to save the object to the database it needs to be associated with a context.
If you want to have a custom initialisation of an object then you can override the awakeFromInsert
and awakeFromFetch
methods/functions.