初始化对象时出错

时间:2013-01-05 00:33:12

标签: ios core-data

下面是一个方法的开始,它一直做同样的事情。但是我收到一个错误:无法在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"];
    }

1 个答案:

答案 0 :(得分: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