Visible SQLite file but invisible data in iOS simulator - ios

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.

Related

+entityForName: nil happens intermittently

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...

Core Data Entity Created But Attributes Not Saving

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.

Reset all saved data in Core Data model

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.

Delete all my data in my Core Data store

I have followed a variety of posts here in SO to delete all the data from an app so I can start over. I have tried:
A) Deleting all the data:
NSArray *entities = model.entities;
for (NSEntityDescription *entityDescription in entities) {
[self deleteAllObjectsWithEntityName:entityDescription.name
inContext:context];
}
if ([context save:&error]) {
...
- (void)deleteAllObjectsWithEntityName:(NSString *)entityName
inContext:(NSManagedObjectContext *)context
{
NSFetchRequest *fetchRequest =
[NSFetchRequest fetchRequestWithEntityName:entityName];
fetchRequest.includesPropertyValues = NO;
fetchRequest.includesSubentities = NO;
NSError *error;
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *managedObject in items) {
[context deleteObject:managedObject];
NSLog(#"Deleted %#", entityName);
}
}
B) Delete the physical data store:
NSError *error;
NSPersistentStore *store = [[self persistentStoreCoordinator].persistentStores lastObject];
NSURL *storeURL = store.URL;
NSPersistentStoreCoordinator *storeCoordinator = store.persistentStoreCoordinator;
[self.diskManagedObjectContext reset]; // there is a local instance variable for the disk managed context
[storeCoordinator removePersistentStore:store error:&error];
[[NSFileManager defaultManager] removeItemAtPath:storeURL.path error:&error];
_diskManagedObjectContext = nil;
C) Perform step A and then step B
In all combinations it appears to run with no errors, but whenever I receive new data (via my HTTP service) and start adding it to the re-initialized data store I get all kinds of duplicate data and various data issues. I usually have to delete and reinstall the app to get the data clean enough to re-initialize.
It should be fairly straightforward. The user logs in. App data is downloaded and saved in the store. User logs out and logs in again or as different ID and new data is brought down.
Any ideas why the above methods are not working?
UPDATE:
I edited my code above to show that I am saving the context and removing the data store file. I still end up with bad leftover data. Could the problem be the multiple contexts we use? We have three contexts we use in the app: a UI-managed context, a background context and a disk-managed context. A notification listener takes care of merging changes in the background context with the disk managed context.
I have tried altering the above code to loop through the objects in all three contexts and we set them all to nil. The authentication code takes care of reinitializing the contexts. Still banging my head on what seems like a simple issue.
After
for (NSEntityDescription *entityDescription in entities) {
[self deleteAllObjectsWithEntityName:entityDescription.name
inContext:context];
}
Save your context
[context save:&error];
(B) doesn't delete the physical store, it just dissociates it from your app for the time being. No doubt you just attach it again shortly thereafter or upon next launch.
Use [[NSFileManager defaultManager] removeItemAtURL:... error:...] actually to delete the file from your disk.
As the other posters have said, you fail to NSManagedObjectContext -save: in (A) so you affect what's in that one context but not in the persistent store. Contexts are just in-memory scratch pads so as soon as you create a new context it'll be able to find everything in the persistent store again unless or until you save the one with the modifications.

Objects Not Being Saved to Core Data Database

I am trying to add objects to a Core Data Database using the following code:
NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init];
managedObjectContext.persistentStoreCoordinator = [[CoreDataController sharedCoreDataController] persistentStoreCoordinator];
Feed *feed = [NSEntityDescription insertNewObjectForEntityForName:#"Feed" inManagedObjectContext:managedObjectContext];
feed.feedID = dictionary[#"feed_id"];
feed.siteURL = dictionary[#"site_url"];
feed.title = dictionary[#"title"];
NSError *error;
if (![managedObjectContext save:&error]) {
NSLog(#"Error, couldn't save: %#", [error localizedDescription]);
}
Feed is a subclass of NSManagedObject. The persistentStoreCoordinator returned from the sharedCoreDataController (a singleton) is the persistentStoreCoordinator from a UIManagedDocument (created or opened when the app launches). As far as I can tell, the document is being created or opened successfully. I am running this code in the simulator, and I'm looking in the directory in which I am saving the Database (the apps Documents directory), but the persistentStore file is not being updated to reflect the new objects being added. Am I doing something wrong? I should also point out that the above code is being executed multiple times on a concurrent, asynchronous queue.
Any help would be much appreciated, thanks in advance.
Update: After the suggestions from Alexander and Duncan, the code above has been updated to reflect the changes. Sadly, however, I haven't noticed any difference (the new data is not appearing in the persistentStore file).
Have you called the line to save your managedObjectContext? How about this:
NSError *error;
if (![managedObjectContext save:&error]) {
NSLog(#"Error, couldn't save: %#", [error localizedDescription]);
}
Try using something like this
NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init];
managedObjectContext.persistentStoreCoordinator = [[CoreDataController sharedCoreDataController] persistentStoreCoordinator];
for (NSDictionary *dictionary in arrayOfData) {
Feed *feed = [NSEntityDescription insertNewObjectForEntityForName:#"Feed" inManagedObjectContext:managedObjectContext];
feed.feedID = dictionary[#"feed_id"];
feed.siteURL = dictionary[#"site_url"];
feed.title = dictionary[#"title"];
}
NSError *error;
if (![managedObjectContext save:&error]) {
NSLog(#"Error, couldn't save: %#", [error localizedDescription]);
}
I would avoid creating a managedObjectContext for each object you insert.
First, using UIManagedDocument is not recommended. It is not intended to be your single app wide context. It is meant for document style applications.
Second, the NSManagedObjectContext that is exposed from the UIManagedDocument doesn't have a NSPersistentStoreCoordinator attached to it. It is a child context of a private NSManagedObjectContext that then has a NSPersistentStoreCoordinator. I suspect that if you used the debugger you may find that your NSManagedObjectContext is missing its NSPersistentStoreCoordinator.
In any event, you are using UIManagedDocument and then trying to attach another NSManagedObjectContext to the same NSPersistentStoreCoordinator. That is a bad design and you should at a minimum remove the UIManagedDocument or stop creating a new NSManagedObjectContext.
What is the point of the new context? What are you trying to solve with this code?

Resources