1

我是一个iOS新手。我正在使用以下函数将新行插入到我的数据库中 -

-(void)insertMetricAction:(NSString *)action andValue:(NSString *)value andStatus:(NSString *)status
{
MetricDb *aDbMessage = (MetricDb *)[NSEntityDescription 
                                      insertNewObjectForEntityForName:@"Metric" 
                                    inManagedObjectContext:localObjectContext];

aDbMessage.action=action;
aDbMessage.value=value;
aDbMessage.status = status;
double timeInMilliSec=[[NSDate date] timeIntervalSince1970]*1000;
NSString* timeStamp = [NSString stringWithFormat:@"%.0f" ,timeInMilliSec];
aDbMessage.timeStamp=timeStamp;

NSError *error;
if (![localObjectContext save:&error]) {
    NSArray* detailedErrors = [[error userInfo] objectForKey:NSDetailedErrorsKey];
    if(detailedErrors != nil && [detailedErrors count] > 0) {
        for(NSError* detailedError in detailedErrors) {
            NSLog(@"  DetailedError: %@", [detailedError userInfo]);
        }
    }
    else {
        NSLog(@"***Getting database error. Error: %@",[error userInfo]);
    }
}

}

相反,如果我想获取现有行并只编辑状态,我将如何使用 iOS 函数来做到这一点?

4

1 回答 1

2

您需要创建一个NSFetchRequest来返回您感兴趣的对象。下面的示例将返回Metric给定实体的实例action

- (MetricDb *) metricWithAction: (NSString *) action
{
    NSFetchRequest * request = [[[NSFetchRequest alloc] init] autorelease];
    [request setEntity: [NSEntityDescription entityForName: @"Metric" inManagedObjectContext: localObjectContext]];
    [request setPredicate: [NSPredicate predicateWithFormat: @"(%K == %@)", 
                            @"action", action]];
    [request setFetchLimit: 1];

    NSError * error = nil;
    MetricDb * metric = [[localObjectContext executeFetchRequest: request error: &error] lastObject];
    if (error) {
        NSLog(@"Error fetching metric - %@", [error localizedDescription]);
    }

    return metric;
}
于 2011-12-12T15:52:13.013 回答