CoreData: error: Failed to call designated initializer on NSManagedObject class

被刻印的时光 ゝ 提交于 2019-11-27 07:57:43
duDE

I think the problem is that Challenges is a NSManagedObject class and you need the designated initializer:

initWithEntity:insertIntoManagedObjectContext:

instead of

Challenges *newChallenge = [[Challenges alloc] init];

Read More..

Jay Versluis

In case you ask yourself "OK, so how to I get that entity?" (like I did), you do this by using the entityForName method like so:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Challenges" inManagedObjectContext:self.managedObjectContext];

Challenges *newChallenge = [[Challenge alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];

Hope this helps, this thread has helped me a lot!

NSManagedObject cannot be just alloc/init like you would normally do with an NSObject. As a matter of fact the designated initializer is: initWithEntity:insertIntoManagedObjectContext:

Now, for the actual error, Apple states in the documentation that:

Important: This method is the designated initializer for NSManagedObject. You must not initialize a managed object simply by sending it init.

So, you could see that you need 2 things in order to initialize it, an NSEntityDescription (which entity you intend to instantiate) and an NSManagedObjectContext (the context that the new object will be created into).

Others have already stated why its not working. Here is how you can cut down on the boilerplate and make your code more readable:

@implementation NSManagedObject(MyPrivateAdditions)

+ (id)insertNewObjectInContext:(NSManagedObjectContext *)context
{
    return [NSEntityDescription insertNewObjectForEntityForName:self.className inManagedObjectContext:context];
}

@end

now you can do:

Challenges *newChallenge = [Challenge insertNewObjectInContext:context];
Łukasz

Additionaly, if your Challenges class is NSManagedObject and date, rounds and shots are defined as its attributes you can add method:

-(void) awakeFromInsert {
     self.date = [NSDate date];
     self.rounds = @(12);
     self.shots = @(5);
}

Each new object will have defined those attributes from its birth.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!