ios


Refresh NSFetchedResultController in Swift


I want to refresh NSFetchedResultController with different predicate if user clicks on an Action Sheet.
Here is the code:
lazy var fetchResultController: NSFetchedResultsController = {
let fetchRequest = NSFetchRequest(entityName: "Debt")
let filterText:String?
let ascending:Bool?
if NSUserDefaults.standardUserDefaults().objectForKey("filterType")?.stringValue == "name" {
filterText = "name"
ascending = true
}
else
{
filterText = "date"
ascending = true
}
let sortDescriptor = NSSortDescriptor(key: filterText, ascending: ascending!)
fetchRequest.sortDescriptors = [sortDescriptor]
let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: CoreDataManager.sharedManager.managedObjectContext, sectionNameKeyPath: filterText, cacheName: nil)
fetchedResultsController.delegate = self
return fetchedResultsController
}()
#IBAction func didTouchUpInsideFilterButton(sender: UIBarButtonItem) {
let alertController = UIAlertController(title: "Filter By:", message: "", preferredStyle: .ActionSheet)
let nameAction = UIAlertAction(title: "Name", style: .Default) { (UIAlertAction) -> Void in
NSUserDefaults.standardUserDefaults().setObject("name", forKey: "filterType")
do {
try self.fetchResultController.performFetch()
} catch {
let fetchError = error as NSError
print("\(fetchError), \(fetchError.userInfo)")
}
};
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (UIAlertAction) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
};
alertController.addAction(nameAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
In the alertAction completion block after calling try self.fetchResultController.performFetch() method fetchResultController is not called again to update the predicate.
Please find a solution.
The chunk of code following the declaration of fetchResultController is for property initialization, and will only be run exactly one time, the first time the property is used. That means that that chunk of code that sets the predicate, etc., will not run when didTouchUpInsideFilterButton is called (unless that reference to self.fetchResultController is the first time fetchResultController is used, which seems unlikely).
You need to explicitly change fetchResultController outside of the initializer when you want to update it.

Related Links

Sending picked image to another view
Jail broken iOS: Communication between tweak and application
Download data from iCloud if app is not running
Move function void to boolean Swift
How to use the side buttons control the volume instead of ringing APP
textFieldDidEndEditing vs didSelectRowAtIndexPath, the later not being called
Converting to Swift 3 (Swift and Firebase Project)
load .html from a local directory that is not compiled in my app
iOS Facebook share video Swift
DateFormatter Changes Date by 500 Years
Localytics ios push device token
getting optional with value even after unwrapping it
Use of unresolved identifier 'GMSPlacesClient' in xcode 7.3.1
Unknown Selector Issue
How to crop my App image like iPhone photo gallary
iOS: How to subscribe a customer to an Automatically Renewable Subscription

Categories

HOME
html5-canvas
gwt
office-js
quickblox
openvpn
windows-10-desktop
silverlight
uwsgi
doorkeeper
graphengine
development-environment
coreos
avr
jgit
image-gallery
next
amplitude
garmin
durandal-2.0
gas
powershell-v2.0
ormlite-servicestack
aspdotnetstorefront
hawq
f2py
sql-server-2014-express
ruamel.yaml
popupwindow
file-manager
skyscanner
svgpanzoom
pvlib
sqlite.swift
ollydbg
gosublime
gradient-descent
linechart
firedac
project-centennial
codeigniter-hmvc
xargs
free-diameter
azure-cdn
mashery
nuget-package-restore
mysql-error-1050
postmark
topojson
codeigniter-upload
xnamespace
viewengine
rabbitvcs
xlform
screen-capture
egl
readline
autopy
database-tuning-advisor
push-api
cocoon-gem
double-quotes
voting
omap
movie
mysql5
jasmin
razor-2
laravel-validation
spread-toolkit
cfile
datasift-python
zephir
angularjs-module
hamlc
layout-manager
eject
gigaspaces
mysql-backup
code-structure
junitperf
ladon
nstreecontroller
hunchentoot
scramble
webshop

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App