NSFetchedResultsController refresh refetch? - iphone

I want to refetch data from my NSFetchedResultsController using a different predicate which is set using a boolean value. How do I refresh NSFetchedResultsController to fetch a new set of data?
- (void)refreshFetchedResultsController {
NSLog(#"refreshFetchedResultsController");
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"Error loading data",
#"Error loading data")
message:[NSString stringWithFormat:
NSLocalizedString(#"Error was: %#, quitting.", #"Error was: %#, quitting."),
[error localizedDescription]]
delegate:self
cancelButtonTitle:NSLocalizedString(#"Cancel", #"Cancel")
otherButtonTitles:nil];
[alert show];
}
}
which calls
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
NSLog(#"i was executed.");
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
TapAppDelegate *appDelegate = (TapAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Favorite" inManagedObjectContext:managedObjectContext];
NSString *sectionKey = #"favname";
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"favname" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
if(showAll == NO){
if(isXSelected == NO){
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isFirst == TRUE"];
[fetchRequest setPredicate:predicate];
}
if(isXSelected == YES){
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isFirst == FALSE"];
[fetchRequest setPredicate:predicate];
}
}
[fetchRequest setSortDescriptors:sortDescriptors];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *frc = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:sectionKey
cacheName:nil];
[sortDescriptor release];
[sortDescriptors release];
frc.delegate = self;
_fetchedResultsController = frc;
[fetchRequest release];
return _fetchedResultsController;
}

Here's how we do it in an application:
// Assuming these exist
NSPredicate * predicate;
NSString * cacheName;
[[fetchedResultsController fetchRequest] setPredicate:predicate];
[NSFetchedResultsController deleteCacheWithName:cacheName];
NSError * error = nil;
[fetchedResultsController performFetch:&error];
if (error) {
// report error
}

Don't forget to set fetchedResultsController = nil before performFetch. Otherwise it will use the old one.

I had similar problem, I couldn't figure out why my collection view doesn't refresh its cells.
Adding the method below fixed my problems.
-(void)didUpdateObjectAtIndexPath:(NSIndexPath *)indexPath{
UICollectionView *strongCollectionView = self.collectionView;
[strongCollectionView reloadItemsAtIndexPaths:#[indexPath]];
}

Related

NSFetchResultsController delegate not getting called

I have the following code:
- (NSFetchedResultsController *)fetchedResultsController {
// Set up the fetched results controller if needed.
if (fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"DiskStory" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"isRemoved == %#", [NSNumber numberWithBool:NO]];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"created" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Set limit
[fetchRequest setFetchBatchSize:25];
// Set batch size
[fetchRequest setFetchLimit:50];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:kSavedStoryCache];
aFetchedResultsController.delegate = self;
fetchedResultsController = aFetchedResultsController;
}
return fetchedResultsController;
}
in my viewDidLoad I have:
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
I was wondering why my :
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
}
delegate, isn't called? I put a break point inside it. Any idea?
I had this problem before, it's not called when you call performFetch for the first time but only when data in fetchedResultsController is actually changed. For instance when you delete object from context that is in this fetch results, delegate will be called.
I think you have used self. at wrong places. Please see the code below; i have added comments to the changes
- (NSFetchedResultsController *)fetchedResultsController {
// Set up the fetched results controller if needed.
if (fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"DiskStory" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"isRemoved == %#", [NSNumber numberWithBool:NO]];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"created" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Set limit
[fetchRequest setFetchBatchSize:25];
// Set batch size
[fetchRequest setFetchLimit:50];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:kSavedStoryCache];
aFetchedResultsController.delegate = self;
fetchedResultsController = aFetchedResultsController; // -> Shouldn't be self.fetchedResultsController
}
return fetchedResultsController; // -> Shouldn't be self.fetchedResultsController
}
Also, if you have synthesize your fetchedResultsController as follows:
fetchedResultsController = _fetchedResultsController
Then in - (NSFetchedResultsController *)fetchedResultsController method you should refer to it as _fetchedResultsController

Using Search bar with Core Data

I have tried various methods and this is the closest I have gotten, but the updating of the table makes all the entries off screen blank, and when I scroll, they all blank out. I am still new and am not entirely sure about implementing a search on core data tableview at all.
If I don't nil things out it dies here:
UPDATE: this is what I am trying now, and I am getting the same crash:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'no section at index 1'
`Recipe *recipe = (Recipe *)[fetchedResultsController objectAtIndexPath:indexPath];` **`Thread 1 received signal SIGABRT`**
#pragma mark -
#pragma mark search bar methods
- (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"searched");
fetchedResultsController = nil;
//============
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Recipe" inManagedObjectContext:managedObjectContext];
if (searchBar.text !=nil) {
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"name contains[cd] %#", searchBar.text];
[fetchedResultsController.fetchRequest setPredicate:predicate];
} else {
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"All"];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"state" ascending:YES];// was name
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,sortDescriptor2, nil];// was 2
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:#"state" cacheName:#"Root"];//#"state"
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptor2 release];
[sortDescriptors release];
//==============
// dismiss the search keyboard
[searchBar resignFirstResponder];
// reload the table view
//[self.tableView reloadData];
}
- (void)configureCell:(RecipeTableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
// Configure the cell //DIES HERE
Recipe *recipe = (Recipe *)[fetchedResultsController objectAtIndexPath:indexPath];
cell.recipe = recipe;
}
In other conditions, it dies when I try to move the table up or down.
Thanks for any guidance or help with understanding and solving this issue!
Rob
tableViewController.m
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Recipe" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"state" ascending:YES];// was name
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor,sortDescriptor2, nil];// was 2
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:#"state" cacheName:#"Root"];//#"state"
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptor2 release];
[sortDescriptors release];
}
return fetchedResultsController;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
self.fetchedResultsController = nil;
self.searchBar.text=#"";
[self.searchBar setShowsCancelButton:NO animated:YES];
[self.searchBar resignFirstResponder];
//self.tableView.allowsSelection = YES;
//self.tableView.scrollEnabled = YES;
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
// added 2 below
//self.fetchedResultsController.delegate = nil;
self.fetchedResultsController = nil;
[self.searchBar setShowsCancelButton:YES animated:YES];
//self.tableView.allowsSelection = NO;
//self.tableView.scrollEnabled = NO;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
// added 2 below
//self.fetchedResultsController.delegate = nil;
self.fetchedResultsController = nil;
NSLog(#"fetchObjects");
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Recipe" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
//NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"state" ascending:YES];// was name
NSSortDescriptor *sortDescriptor2 = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
//NSLog(#"NSInteger value :%#", sortDescriptor);
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor2, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// perform query
NSString *query = self.searchBar.text;
if (query && query.length) fetchRequest.predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[cd] %#", query];
// Edit the section name key path and cache name if appropriate.
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:#"state" cacheName:#"Root"];//#"state"
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
//[sortDescriptor release];
[sortDescriptor2 release];
[sortDescriptors release];
//[self.tableView reloadData];
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
[self.tableView beginUpdates];
}
It doesn't look like you don't ever actually perform the fetch request. From the docs:
After creating an instance, you invoke performFetch: to actually
execute the fetch.
Are you using a UISearchDisplayController? if you are you end up with two tables: one that displays your normal stuff and the other related to the search. You have to treat the tables separately.
There is a writeup of all the code you need to implement searching on tables at How to filter NSFetchedResultsController (CoreData) with UISearchDisplayController/UISearchBar

Core data app is crashing while perform fetch request

I am fetching result from core data entity
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
// Set up the fetched results controller.
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Tutorial" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"id" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
//sorting
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
//release here
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
}
My app is crashing while perform fetch
- (void)viewDidLoad
{
[super viewDidLoad];
//title
self.navigationItem.leftBarButtonItem = self.editButtonItem;
//add song button
UIBarButtonItem *addSongbutton = [[UIBarButtonItem alloc] initWithTitle:#"Add Songs" style:UIBarButtonItemStyleBordered target:self action:#selector(addSongs)];
self.navigationItem.rightBarButtonItem = addSongbutton;
[addSongbutton release];
if (managedObjectContext == nil) {
managedObjectContext = [(SongsWithLyricsAppDelegate *)[[UIApplication sharedApplication]delegate]managedObjectContext];
}
self.title = #"Song List";
//Error message
NSError *error =nil;
if (![[self fetchedResultController]performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
this is Nslog output
Unresolved error (null), (null)
please help
grrr ... always push return in a comment ... I wanted to add that an error output of (null) (null) looks to me as if there is no error, but then the fetch shouldn't return false.
Are you sure fetchedResultsController is not nil when you try to call performFetch on it?
Might it be that your implementation of setFetchedResultsController has a bug?

Empty FetchedResultsController in Core Data

I'm using core data and I have an entity defined called LogRecord. Elsewhere this is populated with objects using:
LogRecord *rec = [NSEntityDescription insertNewObjectForEntityForName:#"LogRecord"
inManagedObjectContext:managedObjectContext];
[rec timestampNow];
rec.moodType = [NSNumber numberWithUnsignedInteger:i];
rec.moodValue = value;
NSError *error = nil;
if (![rec.managedObjectContext save:&error]) {
[DataUtil displayFatalError:error message:#"Failed to save log entry"];
errors++;
}
I've checked and the underlying sqlite database has records in it after using this code.
However, when I try to query for the data using this:
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController == nil) {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"LogRecord"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timestamp" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
}
return fetchedResultsController;
}
It comes up empty as evidenced by [[self.fetchedResultsController sections] count] returning zero.
Any idea how I might debug this? It was working before I tried to break this code out into a different UIViewController....
Never mind.... Somehow the call to [[self fetchedResultsController] performFetch:&error] in viewDidLoad got deleted.

Core Data , NSFetchResultsController leaking

I am not sure if the leak is in my implementation or is it from apple's side....
Instruments indicate me that I have a leak in this line :
if (![[self fetchedResultsController]
performFetch:&error])
I am adding annotations by reading the fetchController to the Map.... like this :
-(void)fillMapWithAnnotations{
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
for(int a=0; a<[[[fetchedResultsController sections]objectAtIndex:0] numberOfObjects]; a++){
LookAround *look=(LookAround *)[fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:a inSection:0]];
if(look){
AddAnnotation *newAnnotation=[[AddAnnotation alloc]initWithLookAround:look];
if(newAnnotation){
[self.mapView addAnnotation:newAnnotation];
[newAnnotation release];
newAnnotation=nil;
}
}
}
}
and I initialize my FetchController like this:
- (NSFetchedResultsController *)fetchedResultsController{
// Set up the fetched results controller if needed.
if (fetchedResultsController == nil) {
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"LookAround" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
}
return fetchedResultsController;
}
I get a leak as soon as i Navigate Back, the ViewController gets Deallocated in which I release my fetch controller object.
The objects that leak are numerous (and of the same type I guess) around the number of records in my sqlite DB
Thanks in advance for your help....
As I noted above, the leak is probably in your AddAnnotation class.