[request2 setEntity:entity];
NSPredicate * predicate2 = [ NSPredicate predicateWithFormat:#"logoFrameNum == %#",[NSNumber numberWithInt:7]];
[request2 setPredicate:predicate2];
NSManagedObject * collectionList2 = [[ managedObjectContext executeFetchRequest:request2 error:&error2] objectAtIndex:0];
NSLog(#"context :%#", deleteContext1);
[managedObjectContext deleteObject:collectionList2];
BOOL yesorno = [collectionList2 isDeleted];
NSLog(#"yesorno : %i", yesorno);
NSError * error10;
NSLog(#"[managedObjectContext ] : %#", deleteContext1);
[collectionList2 release];
if (![managedObjectContext save:&error10]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error10, [error userInfo]);
exit(-1); // Fail
}
There is much more source above it. Change variables or get data from coredata is well performed with the same NSManagedObjectContex I have there. However delete with that context makes me crazy. It crashes without any error message just in
if (![managedObjectContext save:&error10]) {
I tried get a new context and so on and on........a lot..
You are performing a release on an object (collectionList2) that you don't own. This may cause a crash later on (for example, during the save). Try removing the release.
Maybe you are trying to delete a nil object.
Also, you should do all this within one single NSManagedObjectContext.
Try putting your save:error: method right below the deleteObject: call.
Related
I am trying to insert values into core data object, but while saving those values am getting null response, but it's getting updated into Core data database,
Used Code:
AllAssets *allAssets1 = [NSEntityDescription insertNewObjectForEntityForName:#"AllAssets" inManagedObjectContext:context];
allAssets1.assetID = [NSNumber numberWithInt:assetID];
allAssets1.originalassetname = assetName;
[images addObject:[showrelatedAssets objectAtIndex:i]];
[products addObject:allAssets1];
[show_AddtoOffline addRel_Assets:products];
getting null from below NSLog statement,
if ([images count] !=0 ) {
if ([context save:&error])
{
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
Of course it's giving you null. Your data is saved without any error, and you are logging error and [error localizedDescription].
Since there is no error, these will be null.
The method save: of NSManagedObjectContext returns YES if save is successful, and NO if save fails. In the latter case, it also stores the error encountered in the &error address you have passed.
Your if statement should be:
if ([context save:&error]) {
NSLog(#"Save successful");
} else {
NSLog(#"Could not save: %# | %#", error, error.localizedDescription);
}
if ([context save:&error])
{
// This means your data is saved properly
}
What's wrong ? From the doc
(BOOL)save:(NSError **)error
Return Value
YES if the save succeeds, otherwise NO.
So when you enter the loop, save was successful and error is still null.
I have a relatively simple entity. When I create it, set its attributes, and save it, it saves successfully. I can later retrieve it and it is not nil and I get a successful save message from MagicalRecord.
When I retrieve it and try to access any attribute though the attribute is nil. The entity itself is fine but the attributes are all nil. I have checked they are all definitely set correctly before I save.
I haven't encountered this problem before. Why could it be occurring?
NB: This doesn't happen every time. Most times I call the method to create and save this entity it can later be retrieved without any issues. The problem is intermittent but possible to replicate on every run.
Code:
Entity1 *entity1 = [Entity1 MR_createEntityInContext:localContext];
[entity1 setUpEntity:myobject];
EntityChild *entityChild=[EntityChild MR_createEntityInContext:localContext];
[entityChild setUpEntityChild:entity.child withContext:localContext];
[entityChild setEntity1:entity1];
[localContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
}];
Update:
If I look in the sqlite database and search for the entity it actually doesn't exist at all. So MagicalRecord tells me it saves, CoreData lets me retrieve a non-nil object (albeit with nil attributes) but no record exists in the database.
I did not understand ur code standards. As I am new to IOS Development. I Used below code for retrieving.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entityRef = [NSEntityDescription entityForName:#"Entity1" inManagedObjectContext:appDelegate.managedObjectContext];//localContext
[fetchRequest setEntity:entityRef];
NSError *error=nil;
NSArray *detailsArray = [appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (error) {
NSLog(#"Unable to execute fetch request.");
NSLog(#"%#, %#", error, error.localizedDescription);
}
Saving the data
NSManagedObjectContext *context = [appDelegate managedObjectContext];//localContext
NSManagedObject *objectRef = [NSEntityDescription
insertNewObjectForEntityForName:#"Entity1" inManagedObjectContext:context];
[objectRef setValue:#"IOS" forKey:#"Name"];
[objectRef setValue:#"positive" forKey:#"Attitude"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
Hope it helps you...!
Ok, I got to the bottom of this. It wasn't a problem with the code when I did the save. It was actually a problem with some code in another class that was retrieving the data from the wrong context. When I changed the context it worked correctly.
I'm still not sure why this only happened occasionally and not every time the code was run but it's working now.
Thanks for your help anyway everyone.
At the moment I can't see any AUser objects in my sqlite3 app database.
This is the code I have to create a user. Am I missing something? There are no warnings/errors with the code.
AUser *user = [NSEntityDescription insertNewObjectForEntityForName:#"AUser" inManagedObjectContext:_managedObjectContext]; // _managedObjectContext is declared elsewhere
user.name = username; //username is some string declared elsewhere / name is an attribute of AUser
You need to perform a save on the context.
NSError* error = nil;
if(![context save:&error]) {
// something went wrong
NSLog(#"Error saving context: %#\n%#", [error localizedDescription], [error userInfo]);
abort();
}
When you perform a save, data in the context are saved to the persistent store coordinator (hence in your sql store).
P.S. Based on the discussion with #G. Shearer, in production if the context fails to save, you can handle the error gracefully. This means not using abort() call that causes the app to crash.
NSError* error = nil;
if(![context save:&error]) {
// save failed, perform an action like alerting the user, etc.
} else {
// save success
}
You need to call save after creating the object.
Example:
NSError *error;
if ([user.managedObjectContext save:&error]) {
//Success!
} else {
//Failure. Check error.
}
you need to call
NSError *error = nil;
[_managedObjectContext save:&error];
if(error != nil) NSLog(#"core data error: %#",[[error userInfo] description]);
before the object will be persisted to the database
Let's say I load in 1,000 objects via Core Data, and each of them has a user-settable Favorite boolean. It defaults to NO for all objects, but the user can paw through at will, setting it to YES for as many as they like. I want a button in my Settings page to reset that Favorite status to NO for every single object.
What's the best way to do that? Can I iterate through every instance of that Entity somehow, to set it back? (Incidentally, is 'instance' the right word to refer to objects of a certain entity?) Is there a better approach here? I don't want to reload the data from its initial source, since other things in there may have changed: it's not a total reset, just a 'Mass Unfavourite' option.
Okay, I've gotten it to work, but it requires a restart of the app for some reason. I'm doing this:
- (IBAction) resetFavourites: (id) sender
{
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity: [NSEntityDescription entityForName: #"Quote" inManagedObjectContext: [[FQCoreDataController sharedCoreDataController] managedObjectContext]]];
NSArray *results = [[[FQCoreDataController sharedCoreDataController] managedObjectContext] executeFetchRequest: fetch error: nil];
for (Quote *quote in results) {
[quote setIsFavourite: [NSNumber numberWithBool: NO]];
}
NSError *error;
if (![self.fetchedResultsController performFetch: &error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[self.tableView reloadData];
}
This works fine if I close and re-open the app, but it isn't reflected immediately. Isn't that what the reloadData should do, cause an immediate refresh? Am I missing something there?
I'm using core data to save some integer (rate) and then I call save in the context:
HeartRateBeat * beat = [HeartRateBeat heartRateWithHeartRate:rate
ofRecordTitle:self.recordTitle
inManagedObjectContext:document.managedObjectContext];
NSError * error;
[document.managedObjectContext save:&error];
Inside that convenient method I create the object using NSEntityDescription like this:
heartRateBeat = [NSEntityDescription insertNewObjectForEntityForName:#"HeartRateBeat" inManagedObjectContext:context];
(I only copied some important code, just to show what I did.)
I immediately execute a fetch request after every single heart beat inserted and managed object context saved (I save immediately), and the request shows that heart beat does appear to be stored inside Core Data (with growing array of heart beats), but if I restart my app (I'm using simulator BTW) I know things aren't actually getting saved to disk because it starts anew. Checking with SQLite3 command line shows empty tables. What am I missing here?
I get the same problem but I think its just because, I assume, like me you are just stopping the app through xcode and not actually closing it down. I use this code to force a write. Im using a UIManagedDocument, shared through appdelegate, rather than setting everything up manually.
NSError *error = nil;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[[AppDelegate sharedAppDelegate].userDatabase saveToURL:[AppDelegate sharedAppDelegate].userDatabase.fileURL forSaveOperation:UIDocumentSaveForOverwriting completionHandler:nil];
I don't know about you guys, but when I want my Core Data to save, my Core Data better save.
Here's some code that will for sure save all of your Core Datas.
-(void)forceSave {
NSManagedObjectContext * context = self.managedObjectContext; //Get your context here.
if (!context) {
NSLog(#"NO CONTEXT!");
return;
}
NSError * error;
BOOL success = [context save:&error];
if (error || !success) {
NSLog(#"success: %# - error: %#", success ? #"true" : #"false", error);
}
[context performSelectorOnMainThread:#selector(save:) withObject:nil waitUntilDone:YES];
[context performSelector:#selector(save:) withObject:nil afterDelay:1.0];
[context setStalenessInterval:6.0];
while (context) {
[context performBlock:^(){
NSError * error;
bool success = [context save:&error];
if (error || !success)
NSLog(#"success: %# - error: %#", success ? #"true" : #"false", error);
}];
context = context.parentContext;
}
NSLog(#"successful save!");
}
Note that this is BAD CODE. Among other problems, it's not thread-safe and takes too long. However, try using this and deleting some parts of it to your satisfaction :)