1

我有一个 json 响应,我正在尝试使用 NSManagedObject 使用以下代码保存到核心数据:

- (void)breakTrapsToSave:(NSDictionary*)trapsDict
{    
    tempA = [trapsDict objectForKey:@"Envelope"];
    tempB = [tempA objectForKey:@"Body"];
    tempC = [tempB objectForKey:@"getTrapsResponse"];
    tempD = [tempC objectForKey:@"getTrapsResult"];
    tempE = [tempD objectForKey:@"TRAPS"];

    self.lastUpdate = [tempE objectForKey:@"lastUpdate"];
    [self.sharedPrefs setObject:self.lastUpdate forKey:@"last_update"];
    [self.sharedPrefs synchronize];
    NSLog(@"Traps latest updated at: %@", self.lastUpdate);

    tempF = [tempE objectForKey:@"TRAP"];

    [tempF enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        tempA = [tempF objectAtIndex:idx];
        NSString *finalResult;
        NSString *key;

        for (int i=0; i < node.count; i++) {
            tempB = [tempA objectForKey:[node objectAtIndex:i]];
            finalResult = (NSString*)tempB;
            key = [node objectAtIndex:i];

            [self addToCoreData_value:finalResult key:key]; // Core Data
        }
        counter = idx;
    }];

    NSLog(@"Total Traps: %d", counter);
}

#pragma mark - Core Data Methods

- (void)initCoreData
{
    IDANAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
    context = appDelegate.managedObjectContext;
    entityDesc = [NSEntityDescription entityForName:@"Trap" inManagedObjectContext:context];
    managedObject = [[NSManagedObject alloc] initWithEntity:entityDesc insertIntoManagedObjectContext:context];
}

- (void)addToCoreData_value:(NSString*)value key:(NSString*)key
{
    if ([key isEqualToString:@"alarmDistance"] ||
        [key isEqualToString:@"degrees"] ||
        [key isEqualToString:@"id"] ||
        [key isEqualToString:@"polys"] ||
        [key isEqualToString:@"roadNumber"] ||
        [key isEqualToString:@"type"]) {

        [managedObject setValue:[NSNumber numberWithInt:[value intValue]] forKey:key];
    }
    else if ([key isEqualToString:@"lat"] ||
               [key isEqualToString:@"lon"]) {
        [managedObject setValue:[NSNumber numberWithFloat:[value floatValue]] forKey:key];
    }
    else  if ([key isEqualToString:@"isActive"]) {
        BOOL toSet = false;

        if ([value isEqualToString:@"True"]) {
            toSet = YES;
        }
        else {
            toSet = NO;
        }

        [managedObject setValue:[NSNumber numberWithBool:toSet] forKey:key];
    }
    else {
        [managedObject setValue:value forKey:key];
    }


    NSError *error;
    [context save:&error];
}

问题是,我确实记录了,我看到我通过整个enumerateObjectsUsingBlock循环得到了正确的值和键。此外,在:

 - (void)addToCoreData_value:(NSString*)value key:(NSString*)key

我做了一个日志,我看到我也得到了所有的键和值。但是当我打开 sqlite 时,我只看到表中的一行,即最后一个对象。 NSLog(@"Total Traps: %d", counter);- 还打印正确数量的对象(目前为 116 个)。

我做错了什么?

4

1 回答 1

1

看起来您只有一个托管对象。你所做的只是不断地改变它的属性。

您应该做的是为您保存的每个项目创建一个新的托管对象。

于 2013-06-22T14:40:28.943 回答