开发者

coredata-deleting from database and making request

开发者 https://www.devze.com 2023-02-09 10:48 出处:网络
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:

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];
开发者_如何学Go

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


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消