4

我有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;
        }
    }
}

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

编辑: 感谢马丁,代码就像一个魅力。

4

1 回答 1

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如果发生错误,并且
  • 如果没有找到匹配的对象,则为空数组。
于 2013-07-05T21:10:20.290 回答