CoreData: error: No se pudo llamar al inicializador designado en la clase NSManagedObject


Tengo un maldito problema con CoreData. Quiero insertar un nuevo objeto, así que primero tengo que crear uno. Esto se hace por ese código:

Challenges *newChallenge = [[Challenges alloc] init];
[newChallenge setName:@"TestChallenge"];
[newChallenge setRounds:[[NSNumber alloc] initWithInt:12]];
[newChallenge setShots:[[NSNumber alloc] initWithInt:5]];
[newChallenge setDate:[NSDate date]];

Pero sin embargo después del alloc init obtengo este error:

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

Lo que el hack va mal?

Author: Martin R, 2013-02-03

5 answers

Creo que el problema es que Challenges es una clase NSManagedObject y necesitas el inicializador designado:

initWithEntity:insertIntoManagedObjectContext:

En lugar de

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

Leer Más..

 59
Author: duDE,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-18 00:42:31

En caso de que te preguntes " OK, entonces, ¿cómo obtengo esa entidad?"(como hice), puedes hacer esto usando el método entityForName de la siguiente manera:

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

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

Espero que esto ayude, este hilo me ha ayudado mucho!

 30
Author: Jay Versluis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-18 05:32:50

NSManagedObject no puede ser justo alloc/init como lo harías normalmente con un NSObject. De hecho, el inicializador designado es: initWithEntity:insertIntoManagedObjectContext:

Ahora, para el error real, Apple indica en la documentación que:

Importante: Este método es el inicializador designado para NSManagedObject. No debe inicializar un objeto administrado simplemente por enviándolo a init.

Por lo tanto, se puede ver que se necesitan 2 cosas para inicializarlo, un NSEntityDescription (qué entidad pretende crear) y un NSManagedObjectContext (el contexto en el que se creará el nuevo objeto).

 13
Author: Alladinian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-03 10:42:27

Otros ya han declarado por qué no funciona. Aquí está cómo puede reducir el boilerplate y hacer que su código sea más legible:

@implementation NSManagedObject(MyPrivateAdditions)

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

@end

Ahora puedes hacer:

Challenges *newChallenge = [Challenge insertNewObjectInContext:context];
 4
Author: bernstein,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-14 00:58:29

Además, si su clase de Desafíos es NSManagedObject y date, rondas y disparos se definen como sus atributos, puede agregar el método:

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

Cada nuevo objeto tendrá definidos esos atributos desde su nacimiento.

 4
Author: Łukasz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-28 14:07:37