执行向CoreData添加/更新的问题

时间:2013-07-05 20:10:10

标签: ios objective-c database core-data add

我有一个NSArray拥有一些NSDictionary,每次我保存一个NSDictionary对象并将其添加到NSArray,我发送给它添加/更新功能。 我知道我读取的数据是正确的,当我以前添加没有更新功能的数据时,所有数据都插入CoreData,但我想添加更新函数来验证我放的数据。 现在,该函数添加第一个对象,然后一遍又一遍地进入'更新'。 怎么了?

我的代码:

-(void)updateOrAddTrap:(NSMutableDictionary*)trapObject
{
    NSInteger trapID = [trapObject[@"id"] integerValue];
    Trap *trapEntity = nil;
    NSError *error = nil;
    Boolean success = true;

    self.fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Trap"];
    self.predicate = [NSPredicate predicateWithFormat:@"trapID == %d", trapID];
    [self.fetchRequest setPredicate:self.predicate];

    NSArray *results = [self.managedObjectContext executeFetchRequest:self.fetchRequest error:&error];
    if (results == nil)
    {
        // Handle error
        NSLog(@"HANDLE ERROR");
        success = false;
    }
    else if ([results count] == 0)
    {
        // Nothing to update, add new trap
        NSLog(@"NOTHING TO UPDATE | ADD NEW");

        // Create a new record (row)
        trapEntity = [NSEntityDescription insertNewObjectForEntityForName:@"Trap" inManagedObjectContext:self.managedObjectContext];
    }
    else
    {
        NSLog(@"UPDATE EXISTING OBJECT");
        trapEntity = results[0]; // There should be only one object for the ID.
    }


    if (trapEntity != nil)
    {
        // Set properties for new or existing object ...

        // Int
        int alarmDistance = [[trapObject objectForKey:ALARMDISTANCE] intValue];
        int type = [[trapObject objectForKey:TYPE] intValue];
        int roadNumber = [[trapObject objectForKey:ROADNUMBER] intValue];
        int trap_id = [[trapObject objectForKey:ID] intValue];
        int polys = [[trapObject objectForKey:POLYGONS] intValue];
        int degrees = [[trapObject objectForKey:DEGREES] intValue];
        [trapEntity setAlarmDistance:[NSNumber numberWithInt:alarmDistance]];
        [trapEntity setType:[NSNumber numberWithInt:type]];
        [trapEntity setRoadNumber:[NSNumber numberWithInt:roadNumber]];
        [trapEntity setTrapID:[NSNumber numberWithInt:trap_id]];
        [trapEntity setPolys:[NSNumber numberWithInt:polys]];
        [trapEntity setDegrees:[NSNumber numberWithInt:degrees]];

        // Boolean
        BOOL isActive = [[trapObject objectForKey:ISACTIVE] integerValue] == 1 ? YES : NO;
        [trapEntity setIsActive:[NSNumber numberWithBool:isActive]];

        // Float
        float lat = [[trapObject objectForKey:LAT] floatValue];
        float lon = [[trapObject objectForKey:LON] floatValue];
        [trapEntity setLat:[NSNumber numberWithFloat:lat]];
        [trapEntity setLon:[NSNumber numberWithFloat:lon]];

        // NSString
        [trapEntity setDirection:[trapObject objectForKey:DIRECTION]];
        [trapEntity setTrapDescription:[trapObject objectForKey:DESCRIPTION]];
        [trapEntity setPoly0:[trapObject objectForKey:POLYGON_A]];
        [trapEntity setPoly1:[trapObject objectForKey:POLYGON_B]];
        [trapEntity setPoly2:[trapObject objectForKey:POLYGON_C]];
        [trapEntity setPolygonAzimut1:[trapObject objectForKey:POLYGON_A_AZIMUTH]];
        [trapEntity setPolygonAzimut2:[trapObject objectForKey:POLYGON_B_AZIMUTH]];
        [trapEntity setPolygonAzimut3:[trapObject objectForKey:POLYGON_C_AZIMUTH]];
        // etc. for all properties ...

        if (![self.managedObjectContext save:&error])
        {
            NSLog(@"HANDLE ERROR WHEN SAVING THE OBJECT");
            success = false;
        }
    }
}

我很高兴知道如何正确更新,因为我现在也错过了此功能。

修改 感谢马丁,这段代码就像一个魅力。

1 个答案:

答案 0 :(得分:4)

我不确定这是否是您的问题的原因,但是您检查错误 条件或空结果是错误的。它应该是

BOOL success = true;
Trap *trap = nil;
NSArray *results = [self.managedObjectContext executeFetchRequest:self.fetchRequest error:&error];
if (results == nil) {
    NSLog(@"HANDLE ERROR");
    success = false;
} else if ([results count] == 0) {
    NSLog(@"NOTHING TO UPDATE | ADD NEW");
    trap = [NSEntityDescription insertNewObjectForEntityForName:@"Trap" inManagedObjectContext:self.managedObjectContext];
} else {
    NSLog(@"UPDATE EXISTING OBJECT");
    trap = result[0]; // There should be only one object for the ID.
}
if (trap != nil) {
    // Set properties for new or existing object ...
    [trap setTrapID:[NSNumber numberWithInt:trap_id]];
    // etc. for all properties ...

    if (![self.managedObjectContext save:&error]) {
        NSLog(@"HANDLE ERROR WHEN SAVING THE OBJECT");
        success = false;
    }
}

executeFetchRequest返回

  • nil如果发生错误,
  • 如果找不到匹配的对象,则为空数组。