Reputation:
After inserting a new object in core-data representing a new item and then doing a server call on a background thread to insert it into a database on the back end, I retrieve a new id from the server that I would like to insert back into Core-Data.
Can anyone recommend a save new item and call server without losing the new item in the ManagedObjectContext. I would like to make the edit to the managed object without having to do an entire NSFetch with an NSPredicate to find it again but right now, it seems to be disappearing.
Here is my code to store the object locally in Core Data and then go go server. When I get back, however, I don't know how to access this new record.
NSEntityDescription *entity = [NSEntityDescription entityForName:@“Item” inManagedObjectContext:self.managedObjectContext];
// Initialize Record
NSManagedObject *record = [[NSManagedObject alloc] initWithEntity:entity insertIntoManagedObjectContext:self.managedObjectContext];
// Populate Record
[record setValue:name forKey:@“name”];
// Save Record
NSError *error = nil;
if ([self.managedObjectContext save:&error]) {
//code to set up background request
[NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *data, NSError *err) {
if (err) {
} else {
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSInteger insertID = [jsonResults[@"response"][@"insert_id"] integerValue];
self.newid = *(&(insertID));
dispatch_async(dispatch_get_main_queue(), ^{
// //NEED WAY TO INSERT INTO CORE DATA WITHOUT DOING FULL BLOWN FETCH BUT RECORD SEEMS TO BE GONE
});
}
}];
}
Upvotes: 1
Views: 370
Reputation: 119031
2 options, kinda lazy and 'correct'
Assuming that this all originates on the main thread, so record
is inserted into the main context, you can just capture record
in the block and update it. Don't make any other changes to it on any other thread. Also, don't delete it or the context before this operation is finished.
Better, get the objectID
from the new record
, make sure it's a permanent id and not temporary (see obtainPermanentIDsForObjects:error:
). Now for whichever thread you're working on you can request, from the appropriate context, performing a block if you need to, the objectRegisteredForID:
.
Upvotes: 1