iOS - 使用NSEntityDescription和NSManagedObjectContext编辑数据库条目

时间:2011-12-12 15:40:33

标签: iphone ios nsmanagedobjectcontext nsentitydescription

我是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函数进行操作?

1 个答案:

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