coredata-deleting from database and making request

喜你入骨 提交于 2020-01-07 04:41:31

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!