coredata-从数据库中删除并提出请求

时间:2011-02-10 08:24:21

标签: sql objective-c core-data nspredicate

嗨我有点noob whit核心数据,所以我请求你的答案,我可以从数据库中取出数据,这个函数:

NSManagedObject *selectedObject = [[self fetchedResultsController]
    objectAtIndexPath:indexPath];
[[selectedObject valueForKey:@"SOMECOLLUMNNAME"] description];

但我有一个非常大的问题,从数据库删除我已经读过我应该使用NSPredicate我读了tutorial但是我不知道怎么能写一个简单的

DELETE *
FROM Table t
WHERE t.date == 01.01.2011

例如。

你能帮帮我吗

2 个答案:

答案 0 :(得分:1)

嗯。我假设日期对象是NSString,而不是NSDate。

试试这个:

...// 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];

请问您是否需要更多帮助。

答案 1 :(得分:0)

非常感谢Elias

这是我的近乎最终的代码:

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

我希望它可以帮助人们处理同样的问题

再次感谢Elias