1

I am an iOS newbie. I am using the following function to insert new rows to my database -

-(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]);
    }
}

}

If instead, I want to fetch existing rows and just edit the status, how would I do it using iOS functions?

Suchi
  • 9,989
  • 23
  • 68
  • 112

1 Answers1

2

You'll need to create an NSFetchRequest to return the object you're interested in. The example below will return the instance of entity Metric for a given 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;
}
Ashley Mills
  • 50,474
  • 16
  • 129
  • 160
  • If you are using a UITableView, or just accessing lots of entries at once, you should consider an `NSFetchedResultsController`. It simplifies a lot of repeated database fetches. – gurooj Dec 12 '11 at 15:58