I have a project that uses core data and this error happens intermittently. I know that the entity is there because most the time, the app opens and displays the content of the entityName.
1. this is happening in the app delegate and not being segue'd
2. when i do [self.managedObjectModel entities], the entityName is there but app crashes
3. It is not miss-spelled.
4. It occurs the same place, the same time (app start)
NSManagedObjectContext *contOBJ = self.managedObjectContext;
NSEntityDescription *entity;
NSString * entityForNameString = #"MessageLists";
#try {
entity = [NSEntityDescription entityForName:entityForNameString
inManagedObjectContext:contOBJ];
}
#catch (NSException* exception) {
NSLog(#"DANGER DANGER - ERROR FOUND");
NSLog(#"Uncaught exception: %#", exception.description);
// ditch effort to reset manageObject BUT DOES NOT WORK...
[self.managedObjectContext reset];
// ditch effort to reset manageObject BUT DOES NOT WORK...
return nil;
NSLog(#"Stack trace: %#", [exception callStackSymbols]);
// Reset the store
}
#finally {
NSLog(#"finally");
}
NSFetchRequest *fetcher = [[NSFetchRequest alloc] init];
// need to define a predicate that will institute weather a message thread is deleted or NOT
[fetcher setEntity:entity];
NSError *error;
NSLog(#"All Records is %#",[contOBJ executeFetchRequest:fetcher error:&error]);
return [contOBJ executeFetchRequest:fetcher error:&error];
Don't use that old stringly typed stuff, just do this
NSFetchRequest *fetchRequest = [MessageLists fetchRequest];
NSError *error;
NSLog(#"All Records is %#",[context executeFetchRequest:fetchRequest error:&error]);
The reason why my issue was intermittent is not because of my codes but rather changes to iOS 10. Apparently, apple made changes to the way core data is init and declared in the AppDelegate.
Starting in iOS 10 and macOS 10.12, the NSPersistentContainer handles
the creation of the Core Data stack and offers access to the
NSManagedObjectContext as well as a number of convenience methods.
Prior to iOS 10 and macOS 10.12, the creation of the Core Data stack
was more involved.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/InitializingtheCoreDataStack.html
As it turns out, even if I implemented:
NSFetchRequest *fetchRequest = [MessageLists fetchRequest];
NSError *error;
NSLog(#"All Records is %#",[context executeFetchRequest:fetchRequest error:&error]);
I would still arrive at the same issue. Besides, I haven't updated my AppDelegate's Core Data codes since iOS 8...
Related
I have an app that saves a lot of data in the phone. I am using the following code:
- (void)datostickets:(NSString*)cod local:(NSString*)nombre{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *ticket =[NSEntityDescription entityForName:#"History" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:ticket];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(codigo = %#)", cod];
[request setPredicate:pred];
//NSManagedObject *matches = nil;
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
if ([objects count] == 0) {
NSManagedObject *nuevoticket = [NSEntityDescription insertNewObjectForEntityForName:#"History" inManagedObjectContext:context];
[nuevoticket setValue:[NSString stringWithFormat:#"%#",cod] forKey:#"codigo"];
[nuevoticket setValue:self.idloc forKey:#"actividad"];
[nuevoticket setValue:nombre forKey:#"localidad"];
NSLog(#"GRABA: %#",cod);
} else {
NSLog(#"VERIFICA");
check++;
}}
It saves fine, but the problem happens if the app crashes (I think it only happen this way, also the app only crashes when I am manipulating the data).
When the app crashes Core Data starts acting really weird, and it deletes the recent data that I saved, but somehow some of the old data is not deleted (apparently when I change of viewController Core Data makes a commit, so this old data is not deleted).
This problem is solved when I navigate trough the app windows and it starts again if the app crashes. I know the problem is pretty weird.
So, is there a way to solve this? maybe there is a commit statement or something like that.
Thanks for the help
Use [context save:&error] to commit changes.
Use context save& error .or if you using magicall records use MR_Save to persistent store and wait method other wise it is Unable to delete data from storage.
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.
I have a method which allows the user to export a .csv file of all data in my Core Data model. I'm using the wonderful CHCSV Parser after performing a fetchRequest to fetch the stored results. Once the .csv has been created, it gets attached to an email and exported from the device. This all works fine, the issues come when I delete the data.
I am using a somewhat popular technique to delete my data (by popular I mean it has been recommended on lots of Stack Overflow answers I have came researched). I simply fetch all objects and delete them one by one.
// Create fetchRequest
NGLSAppDelegate *appDelegate = (NGLSAppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"NGLS"
inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
// Delete objects
for (Model *results in fetchedObjects) {
[context deleteObject:(id)results];
NSLog(#"NGLS objects deleted");
};
My model is simple and only has two entities, so I use the same code for the other Admin entity too. This is all fine, all objects are deleted, and I can confirm this by doing another fetchRequest which returns the object count for each entity - both have a count of zero. The problem occurs when I try to save data back to either entity after the delete has been executed.
The ViewController with the above code is an "Admin" control screen, where the user can login and also export the data. So when the user logs in, here is the code to save:
// Save login details
[_managedObjectAdmin setValue:user forKey:#"userLogin"];
[_managedObjectAdmin setValue:site forKey:#"siteLocation"];
NSError *error;
[[self.managedObjectAdmin managedObjectContext] save:&error];
I then perform the fetchRequest above and export all data when the "Export" button is pressed. After that is complete, when I try to login on the same ViewController, the output is:
2014-10-27 12:43:49.653 NGLS[19471:607] <NSManagedObject: 0x7a8c2460> (entity: Admin; id: 0x7a82e3e0 <x-coredata://3C9F3807-E314-439C-8B73-3D4459F85156/Admin/p30> ; data: <fault>)
If I navigate back to another ViewController (using my navigation controller), then go back to the "Admin" control screen and try to login again, I get this output:
2014-10-27 12:44:04.530 NGLS[19471:607] *** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'CoreData could not fulfill a fault for '0x7a82e3e0 <x-coredata://3C9F3807-E314-439C-8B73-3D4459F85156/Admin/p30>''
(I can post the full log if requested).
I have tried many things in an attempt to resolve this issue. Core Data is complex and I dont quite understand what I need to do to fix this. I have tried to delete the persistentStore and create it again, and the same with the managedObjectContext but nothing I have tried has worked. I implemented a resetStore method in my AppDelegate to delete and rebuild the store as follows:
- (void)resetStores {
NSError *error;
NSURL *storeURL = [[_managedObjectContext persistentStoreCoordinator] URLForPersistentStore:[[[_managedObjectContext persistentStoreCoordinator] persistentStores] lastObject]];
// lock the current context
[_managedObjectContext lock];
[_managedObjectContext reset];//to drop pending changes
//delete the store from the current managedObjectContext
if ([[_managedObjectContext persistentStoreCoordinator] removePersistentStore:[[[_managedObjectContext persistentStoreCoordinator] persistentStores] lastObject] error:&error])
{
// remove the file containing the data
[[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
//recreate the store like in the appDelegate method
[[_managedObjectContext persistentStoreCoordinator] addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error];//recreates the persistent store
}
[_managedObjectContext unlock];
}
And also tried this method:
- (NSPersistentStoreCoordinator *)resetPersistentStore
{
NSError *error = nil;
if ([_persistentStoreCoordinator persistentStores] == nil)
return [self persistentStoreCoordinator];
_managedObjectContext = nil;
NSPersistentStore *store = [[_persistentStoreCoordinator persistentStores] lastObject];
if (![_persistentStoreCoordinator removePersistentStore:store error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
// Delete file
if ([[NSFileManager defaultManager] fileExistsAtPath:store.URL.path]) {
if (![[NSFileManager defaultManager] removeItemAtPath:store.URL.path error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
// Delete the reference to non-existing store
_persistentStoreCoordinator = nil;
NSPersistentStoreCoordinator *r = [self persistentStoreCoordinator];
return r;
}
But neither of these work. What I have found to work is after the export has completed, by closing and reopening the app everything works as normal again. I have tried to figure out what process occurs when closing/opening the app in regards to Core Data but I just don't know what to look for. I have researched many questions on Stack Overflow and tried all the solutions but nothing works for me. I really need some help on this, or else I'm going to have to force the user to quit the app after the export is done by a exit(0); command (because it's not getting submitted to the App Store, its for in-house employees) although I don't want that solution, surely there is a way I can just reset my database and continue to use the app without having to shut it down every time. Thanks in advance.
References:
Deleting all records from Core Data
Reset a Core Data persistent store
How do I delete all objects from my persistent store in Core Data
I have managed to solve the issue by simply refreshing the view. By calling my viewDidLoad method after the export is complete I create a new managedObject ready to use as normal, without leaving that ViewController or exiting the app altogether.
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib
// Create fetchRequest
NGLSAppDelegate *appDelegate = (NGLSAppDelegate *)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Admin" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
// Fetch last object
Model *admin = [fetchedObjects lastObject];
// Populate login fields with last stored details
if (admin.userLogin == nil) {
//NSLog(#"Login empty");
} else {
self.usernameField.text = admin.userLogin;
self.siteLocationField.text = admin.siteLocation;
}
// Create new managed object using the Admin entity description
NSManagedObject *ManagedObjectAdmin;
ManagedObjectAdmin = [NSEntityDescription insertNewObjectForEntityForName:#"Admin"
inManagedObjectContext:context];
// Declare managed object
self.managedObjectAdmin = ManagedObjectAdmin;
// Save context
NSError *saveError = nil;
[context save:&saveError];
// ... more stuff
}
The solution was so simple all along. I will leave this question/answer up so other people can benefit from it if they find themselves in my situation. Thanks.
EDIT: Re-creating the managedObjectAdmin anywhere after the export works too, there is no specific need to call the viewDidLoad method. After the export has completed, I can simply create the new managedObject and save the context and continue using the app as normal, without having to navigate to another ViewController first or restarting the app.
I am using coredata to load a sqllite DB that has mainly static data. I make sure through code that the sqlite DB exists, and then do a
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *e = [[model entitiesByName] objectForKey:#"Item"];
[request setEntity:e];
NSError *error;
// Here I never get any data
NSArray *result = [context executeFetchRequest:request error:&error];
if (error) {
[NSException raise:#"Fetch failed"
format:#"Reason: %#", [error localizedDescription]];
}
However I never get any data out of the DB!! I get no errors either, all I get is an empty array for result.
I know the sqliteDB has data in it, what could be going wrong?
Update :
So the DB file does have values, but the behavior is inconsistent, It works fine the first time I run the app in a simulator , but If I reset Content And Settings on the simulator and then do another build, the app cannot load any data from the DB, no error or anything, it just cannot find any entries in the DB!!
The problem was intenral, I was not loading data properly.
i've created an app that uses Core-data. Now i want to see the data that i've stored in various entities in that app. App has been installed in iOS-simulator (7.0.3)
This did not help
ScreenShot:
And here is how I am saving the data..
EffController *newController = [NSEntityDescription insertNewObjectForEntityForName:#"EffController" inManagedObjectContext:self.managedObjectContext];
newController.name=#"fgfghjfghj";
newController.uniqueUID= #"ffghfg";
newController.parentOutputID = #0;
newController.localIP=#"***.***.***.***";
newController.localPort= #XXXX;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]
initWithEntityName:#"EffControllerType"];
NSError *requestError = nil;
/* And execute the fetch request on the context */
NSArray *types = [self.managedObjectContext executeFetchRequest:fetchRequest error:&requestError];
for (EffControllerType *type in types) {
if ([type.name isEqualToString:#"***********"]) {
newController.type= type;
break;
}
}
NSError *error = nil;
if (![newController.managedObjectContext save:&error]) { //here is the mistake.
//It should be self.managedobjectContext
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
Edit After long discussion with #HaniIbrahim problem was solved… But still not clear about why the content was visible in app, not in sqlite file? & why context for managed object? Can anybody help to find real issue behind the topic?
After you insert, update or delete anything in CoreData you have to save context to actual apply your updates
NSError *error = nil;
[context save:&error]; // context is your managedObjectContext that you use to communicate with coreData
Edit
After you post your code I found that you are using two context self.managedObjectContext and newController.managedObjectContext ?
You can view the data by using SQLite Manager plugin for Firefox. Open firefox -> Install the plugin -> Open the plugin -> navigate to the below path using Open File option
Library/Application Support/iPhone Simulator/VERSION_OF_YOUR_SIMULATOR/Applications/YOUR_PROJECT(Usually in alphanumeric)/YOUR_DB_FILE.sqlite
That should do.
There are number of plugins and applications available similar to SQLite Manager. You may choose that as per your desire.