0

下面是一个从头到尾做同样事情的方法的开始。但是我收到一个错误:无法在 NSManagedObject 类 'Car' 上调用指定的初始化程序

我做错了什么,谢谢。

- (Car*) initWithJSONData:(NSDictionary *)responseData {
    BOOL isActive;
    self = [super init];

    Car*coreDataCar =(Car*)[NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:[self managedObjectContext]];
    //Check if car is active or deactive.
    if (![responseData valueForKeyIsNull:@"Car Status"]) {
        int carStatus = [[responseData valueForKey:@"Car Status"] intValue];
        if (carStatus == 1 ) {//active
            isActive=YES;
        }else if( carStatus == 2 ){
            isActive = NO;
        }
    }


    if (![responseData valueForKeyIsNull:@"Name"]) {
        [coreDataCar setValue:[responseData valueForKey:@"Name"] forKey:@"name"];
    }
    NSLog(@"user count = %@",[responseData valueForKey:@"UserCount"]);//Sometimes it crashes here, others it doesnt
    if (![responseData valueForKeyIsNull:@"UserCount"]) {
        //[responseData valueForKey:@"UserCount"];
        [coreDataCar setValue:[responseData valueForKey:@"UserCount"] forKey:@"userCount"];
    }
4

1 回答 1

1

这是它抱怨的电话:

 self = [super init];

稍后你这样做:

Car*coreDataCar =(Car*)[NSEntityDescription insertNewObjectForEntityForName:@"Car" inManagedObjectContext:[self managedObjectContext]];

您应该摆脱这两个调用并将它们替换为以下内容:

- (id) initWithJSONData:(NSDictionary *)responseData
 inManagedObjectContext:(NSManagedObjectContext *) moc {

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Car"
                                              inManagedObjectContext:moc];
    if (self = [super initWithEntity:entity insertIntoManagedObjectContext:moc]) {

        ...

    }
    return self;
}

另请注意,init 方法通常具有返回类型id

于 2013-01-05T04:16:45.403 回答