问题
Hi I am a bit noob whit core-data so I request for your answer, I can pull out data from database whit this functions:
NSManagedObject *selectedObject = [[self fetchedResultsController]
objectAtIndexPath:indexPath];
[[selectedObject valueForKey:@"SOMECOLLUMNNAME"] description];
But I have a really big problems whit deleting from database I have read that I should use NSPredicate I read the tutorial but I do no figure out how can I write a simple
DELETE *
FROM Table t
WHERE t.date == 01.01.2011
for example.
Can You Help me pls
回答1:
Hmm. I assume the date object is a NSString, not a NSDate.
Try this:
...// your code
NSPredicate * predicate = [NSPredicate predicateWithFormat:@"date == %@", @"01.01.2011"];
[request setPredicate:predicate];
// Execute the fetch -- create a mutable copy of the result.
NSError * error = nil;
NSMutableArray * mutableFetchResults = [[yourManagedObjectContext executeFetchRequest:request error:&error] mutableCopy];
for (int i = 0; i < [mutableFetchResults count]; i++)
{
YourEntity * object = (YourEntity*)[mutableFetchResults objectAtIndex:i];
[yourManagedObjectContext deleteObject:object];
}
[mutableFetchResults release];
Pls ask if you need more help.
回答2:
Thanks a lot Elias
Here is my nearly final code:
-(void)deleteLastDate{
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:0];
NSString *startDate=[[NSString alloc]initWithString:@"01.01.2011"];//[[managedObject valueForKey:@"date"] description]];
NSManagedObjectContext *moc = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date == %@)", startDate];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:[NSEntityDescription entityForName:[entity name] inManagedObjectContext:moc]];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:request error:&error];
int aegedInt = [results count];
for (int i = 0; i<aegedInt; i++) {
[moc deleteObject:[results objectAtIndex:i]];
}
}
I hope it will help people dealing whit same problem
Thanks again Elias
来源:https://stackoverflow.com/questions/4954813/coredata-deleting-from-database-and-making-request