Reputation: 2184
When i load main TableView list of items from CoreData it shows perfectly by:
let fetchRequest:NSFetchRequest<Identity> = Identity.fetchRequest()
do
{
identities = try DatabaseController.getContext().fetch(fetchRequest)
print("number of results: \(identities.count)")
for identity in identities as [Identity]
{
print("\(identity.pName!) is \(identity.accuracy)% Robesper. Updeted \(identity.lastModified!).")
}
}
catch
{
print("Error fetchRequest in ViewWillApper: \(error)")
}
Deleting also works well, so i created a new NavigationController and a View for Adding a new object.
To check the list and figure out what is the problem (obviously), i output the list.count . Because when i load the main TableView with list new ITEM does not appear basically. However, when i restart the SIMULATOR, it shows all items.
So 1. Created new object.
> number of results: 3 Hello World is 99% Robesper. Updeted 2017-07-08 > 17:50:30 +0000. Sex is 99% Robesper. Updeted 2017-07-27 17:56:12 > +0000. test is 99% Robesper. Updeted 2017-07-27 18:03:28 +0000.
Now -> Go to TableView -> I checked the list at the viewDidLoad and viewWillAppear.
It is "0". Great, because it is not messy and we can check now from CoreData list in the TableViewController.
number of results viewDidLoad: 0 viewWillAppear: 0 number of results: 2 Sex is 99% Robesper. Updeted 2017-07-27 17:56:12 +0000. Hello World is 99% Robesper. Updeted 2017-07-08 17:50:30 +0000. after fetch: 2
MAYBE, because of termination of the program we saved it from AppDelegate?
func applicationWillTerminate(_ application: UIApplication)
{
DatabaseController.saveContext()
}
I pasted the save .saveContext() on ViewWillAppear, didn't work. WHAAAAT? What am i doing wrong guys? PLEASE! SAVE ME :D
Upvotes: 0
Views: 347
Reputation: 2184
fetch process/setting variables ... then ...
I thought I should clean temporary variables for storing data. So I used DatabaseController.getContext().delete(identity)
to keep it clean.
However, there is no need to do that in SWIFT, because this MANAGERs can do it for you. All you need - SAVE'n'GO to reload the table/Data list
Just commenting this solved all problems)
//DatabaseController.getContext().delete(identity)
DatabaseController.saveContext()
Upvotes: 0
Reputation: 1698
You should reload the table when view appear in main queue after fetching the result from core data.
DispatchQueue.main.async {
tableView.reloadData()
}
Upvotes: 1
Reputation: 89152
You should save the context when you are done inserting the item.
The views won't update themselves. You need to refetch and call reloadData on your table view. Or use an NSFetchedResultsController to have a table be connected to a CoreData query: https://developer.apple.com/documentation/coredata/nsfetchedresultscontroller
Upvotes: 0