1

I have some objects stored in core data. Now I want to fetch all objects but one row at a time and after i finish my operation on it, I want to delete only that row/object from core data. And again fetch next row and delete that row, and so on until core data is empty. (with good approach) My code to store objects in core data :

-(BOOL)saveProduct:(AddProduct *)addProduct withImageNSData:(NSData *)imageNSData error:(NSError *)error{
    NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:self.managedObjectContext];
    Device *device = (Device *)object;
    [device setValue:addProduct.CurrencyType forKey:@"currencyType"];
    [device setValue:[NSNumber numberWithDouble:addProduct.Latitude] forKey:@"latitude"];
    [device setValue:[NSNumber numberWithDouble:addProduct.Longitude] forKey:@"longitude"];
    [device setValue:[NSNumber numberWithDouble:addProduct.Price] forKey:@"price"];
    return [self.managedObjectContext save:&error];
}
Wain
  • 118,658
  • 15
  • 128
  • 151
Ravi
  • 800
  • 2
  • 12
  • 28
  • here https://developer.apple.com/library/ios/documentation/CoreData/Reference/NSFetchedResultsController_Class/ - the answer u need – hbk Apr 19 '16 at 06:22
  • Why do you want to do that? – Wain Apr 19 '16 at 06:48
  • @ Wain, I have to create an opeation queue (in core data) when mobile is offline, and whenever device comes online, I want to fetch row one by one and perform operation(hit web service) on that row and then delete that row from core data , and then take second row and so on until core data queue empty. – Ravi Apr 19 '16 at 11:59
  • Check out [Matthew's answer here](http://stackoverflow.com/questions/4293026/coredata-edit-overwrite-object) for fetching – Bryan Norden Apr 20 '16 at 00:16

1 Answers1

0

This will fetch all of the Devices and iterate through them, deleting the objects after you've performed your work on them:

NSManagedObjectContext *context = self.managedObjectContext;
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Device"];

//Fetch all of the Devices
NSError *error;
NSArray *allDevices = [context executeFetchRequest:fetchRequest error:&error];
if (error) {
    NSLog(@"Error fetching devices! %@", error);
    return;
}

for (Device *device in allDevices) {
    // Perform your operation on the device

    [context deleteObject:device];
}
[context save:NULL];
Alex King
  • 71
  • 2
  • 5