lundi 23 mars 2015

Best Practise to Delete and Create managedObjects

In my application i am using core data. I have 2 contexts used, one is foreground context used by main to populate the data load table using NSFetchedResultsController and other context which us used by background threads to save data to core data.



[MYDataModel refreshUserData:^(BOOL success, NSError *error){

[self.fetchedResultContoller performFetch:nil];
[self.tableview reloadData];
}]


In the backGround Queue once data is downloaded and parsed.



// Fetch and Delete all Old Objects
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyModel" inManagedObjectContext:self];
[fetchRequest setEntity:entity];
NSArray *allObjects = [self.context executeFetchRequest:fetchRequest error:nil];

for (NSManagedObject *object in allObjects){
[self.managedObjectContext deleteObject: object];
}

// Create new objects

for (id dict in responseJson) {

// Create object
MyModel *object = [NSEntityDescription insertNewObjectForEntityForName:@"MyModel"
inManagedObjectContext:context];
//set all poperties
object.name = dataContiner[@"name"];

//Save
[self.context save:nil];
}

//calls the blocks passed from ViewController
completionBlock(YES, nil);


Reason i delete old objects before loading the new data is because server will return different results every i get the data.


In between object deletion and TableView Refresh, If i scroll the tableview. It will access and fault object and the application will crash. What would be the approach here ?




Aucun commentaire:

Enregistrer un commentaire