NSFetchedResultsController indexPathForObject not counting sections - ios

I am updating a download view/button on a cell, and when I go to update my cell, I am not getting the correct section.
My code to get the index and update the download progress is this:
Object *obj = (Object *)notification.object;
NSIndexPath *index = [self.fetchedResultsController indexPathForObject:obj];
MyTableViewCell *cell = (MyTableViewCell *)[self.tableView cellForRowAtIndexPath:index];
DownloadProgressButtonView *buttonView = (DownloadProgressButtonView *)cell.accessoryView;
NSNumber *progressLong = [notification.userInfo objectForKey:#"progress"];
float progress = [progressLong floatValue];
NSNumber *totalBytesLong = [notification.userInfo objectForKey:#"totalBytes"];
float totalBytes = [totalBytesLong floatValue];
buttonView.progress = progress *.01;
float totalDownloadEstimate = totalBytes / 1.0e6;
float megaBytesDownloaded = (progress *.01) * totalDownloadEstimate;
cell.bottomLabel.text = [NSString stringWithFormat:#"%.1f MB of %.1f MB", megaBytesDownloaded, totalDownloadEstimate];
If I have two objects, each in a different section, they have the same row (0). When I go to update my cell, it updates the cell in section 1 instead of section 0. How do I fix this?
I can put whatever other code is needed. It works perfectly if I just disable sections in my NSFetchedResultsController.
My NSFetchedResultsController and delegates.
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Object" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *nameString = [[NSSortDescriptor alloc] initWithKey:self.sectionSortDescriptor ascending:NO];
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:self.sortDescriptor ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObjects:nameString,descriptor, nil]];
NSString *downloadStartedString = #"Preparing to download";
NSString *downloadingString = #"Downloading";
NSString *downloadPausedString = #"Download paused";
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"(downloaded == YES) OR (downloadStatus like[cd] %#) OR (downloadStatus like[cd] %#) OR (downloadStatus like[cd]%#)",downloadPausedString, downloadStartedString,downloadingString];
[fetchRequest setFetchBatchSize:20];
_fetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext sectionNameKeyPath:self.sectionNameString
cacheName:nil];
_fetchedResultsController.delegate = self;
self.fetchedResultsController = _fetchedResultsController;
return _fetchedResultsController;
}
/*
NSFetchedResultsController delegate methods to respond to additions, removals and so on.
*/
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.tableView;
switch(type)
{
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:#[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:(StudioTableViewCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[tableView insertRowsAtIndexPaths:#[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
break;
case NSFetchedResultsChangeMove:
NSLog(#"A table item was moved");
break;
case NSFetchedResultsChangeUpdate:
NSLog(#"A table item was updated");
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
[self.tableView endUpdates];
}
Finally when the download status changes, I update the object and send a notification to update the cell with the new status:
- (void)updateCell:(NSNotification *)notification
{
Object *obj = (Object *)notification.object;
NSIndexPath *index = [self.fetchedResultsController indexPathForObject:obj];
[self.tableView reloadRowsAtIndexPaths:#[index] withRowAnimation:UITableViewRowAnimationFade];
}

Updating cells this way is not reliable. A cell updated in such a way will sooner or later be reused. The cell's subviews will be re-configured by tableView:cellForRowAtIndexPath:, based on the data provided by the datasource.
You should make changes to the Object itself (instead of passing them in notification's userInfo) and save the managed object context. Then NSFetchedResultsControllerDelegate callbacks will fire, allowing you to reload the corresponding row. Then you should set all the properties of MyTableViewCell in configureCell:atIndexPath.
And the configureCell: method should be called from cellForRowAtIndexPath method, not from the fetched results controller delegate method. The general pattern is to call reloadRowsAtIndexPaths: in controllerDidChangeObject:. Otherwise you can run into some cell reuse issues.
An idea on how the code should look like:
- (void)updateCell:(NSNotification *)notification
{
//depending on your Core Data contexts setup,
// you may need embed the code below in performBlock: on object's context,
// I omitted it for clarity
Object *obj = (Object *)notification.object;
//save changes to the object, for example:
NSNumber *progressLong = [notification.userInfo objectForKey:#"progress"];
obj.progress = progressLong;
//set all the properties you will need in configureCell:, then save context
[obj.magagedObjectContext save:&someError];
}
then the fetched results controller will call controllerDidChangeObject:, in this method you should reload the row:
case NSFetchedResultsChangeUpdate:
[self.tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationNone];
break;
finally, configure the cell (let's assume that you call configureCell:atIndexPath from tableView:cellForRowAtIndexPath:):
- (void)configureCell:(MyTableViewCell*)cell atIndexPath:(NSIndexPath*)indexPath {
Object *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
DownloadProgressButtonView *buttonView = (DownloadProgressButtonView*) cell.accessoryView;
buttonView.progress = object.progress.floatValue *.01;
//and so on
}

Related

NSfetchedResultsController changes not reflecting to UI

Problem with NSFetchedResultsController is that I fetched the data and it populates the UITableView with cacheName set to nil. Later when I change the predicate of NSFetchedResultsController and called perfromFetch, it won't refreshes the UITableView however the data inside NSFetchedResultsController is updated. One thing more, NSFetchedResultsControllerDelegate methods are also not invoking.
Thanks in Advance.
Edited: Added Code
NSFetchedResultsControllerDelegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id )sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
case NSFetchedResultsChangeUpdate:
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}
NSFetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController) {
return _fetchedResultsController;
}
NSManagedObjectContext *context = [GmailDBService sharedService].managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Thread"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"historyId" ascending:NO];
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"SUBQUERY(messages, $m, ANY $m.labels.identifier == %#).#count > 0", self.label.identifier];
fetchRequest.sortDescriptors = #[sortDescriptor];
fetchRequest.fetchBatchSize = 20;
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];
_fetchedResultsController.delegate = self;
[_fetchedResultsController performFetch:nil];
return _fetchedResultsController;
}
Predicate Refreshing
- (IBAction)unwindToThreadsController:(UIStoryboardSegue *)segue
{
self.fetchedResultsController.fetchRequest.predicate = [NSPredicate predicateWithFormat:#"identifier == %#", #"15f1919682399cc9"];
[self.fetchedResultsController performFetch:nil];
}
fetchedResultsController are not expensive. You should not be afraid to create and destroy them as needed. When you need to change the predicate discard the current fetchedResultsController and create a new one. Don't forget to reload the tableView after you do so.
The changes aren't triggering the fetchedResultsController because you are monitoring threads, but your predicate is based on messages. So when a message is changed it does not trigger a change in the fetchedResultsController. The controller only monitors changes to one entity and does not expect changes to other entities to effect it. You can fix this in a few ways:
setup your fetchedResultsController to look at message and group them by threads, then only display every section (ie thread) as a row.
every time you change a message also change its thread (message.thread.threadId = message.thread.threadId will count as a change as far as the fetchedResultsController is concerned).
Also fetchBatchSize isn't respected by a fetchedResultsController so you should remove it for clarity.

Objective C - Fetch Results Controller fetching less objects after insert

I have a chat panel in an iOS application using NSFetchResultController. Fetching occurs as:
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
DataSource *dataSource = [DataSource getInstance];
[NSFetchedResultsController deleteCacheWithName:#"MessageList"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:_CHAT_MESSAGE_ENTITY_ inManagedObjectContext:dataSource.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
//Predicate
DataClass *dataClass = [DataClass getInstance];
NSPredicate *predicate;
if ([self.chatType intValue] == SINGULAR_CHAT_TYPE) {
Contact *receiver = [self.members objectAtIndex:0];
predicate = [NSPredicate predicateWithFormat:#"(senderUid LIKE %# AND receiverUid LIKE %#) OR (senderUid LIKE %# AND receiverUid LIKE %#)", [dataClass getKeychainValueWithKey:_USER_ID_IDENTIFIER_], receiver.contactUid, receiver.contactUid, [dataClass getKeychainValueWithKey:_USER_ID_IDENTIFIER_]];
}
else { // group chat
}
[fetchRequest setPredicate:predicate];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"messageDate" ascending:YES];
NSArray *sortDescriptors = #[sortDescriptor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:dataSource.managedObjectContext sectionNameKeyPath:#"messageId" cacheName:#"MessageList"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"%#:Unresolved error in fetchedResultsController performFetch %#List, %#", _CHAT_MESSAGE_ENTITY_,error, [error userInfo]);
//abort();
}
return _fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.chatTableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[self.chatTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.chatTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
default:
return;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.chatTableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:#[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
// case NSFetchedResultsChangeUpdate:
// [self configureCell:[chatTableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
// break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:#[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.chatTableView reloadData];
[self.chatTableView endUpdates];
}
This fetching works normal, when I open the view controller all previous messages are seen on the table as they should be. However, when I type a new message and press "send" button, not only the new message but also last message before it is not getting fetched.
I get the number of rows, see there are 2 missing objects.
Still, if I stop app and run again, these last 2 messages are getting fetched and shown.
The same problem is occuring conversations panel. In other words, after sending message my conversation view controller needs to be updated. However, its last conversations (chosen one) is getting lost.
I'm saving the message and conversations as:
DataSource *ds = [DataSource getInstance];
ChatMessage *newMsg = (ChatMessage*)[ds createInsertObject:_CHAT_MESSAGE_ENTITY_];
[newMsg loadFromDictionary:tmpDict];
Chat *chat = (Chat*)[ds findOrCreateWithIdentifier:[[headers objectForKey:CHAT_TYPE] stringValue]:[headers objectForKey:#"receiverUid"] :_CHAT_ENTITY_];
[chat loadHeaders:headers andMessage:newMsg];
newMsg.chat = chat;
[ds coreDataSaveContext];
And after this saving, I'm telling to my chat view controller:
- (void)refreshPage {
[self.fetchedResultsController performFetch:nil];
[self.chatTableView reloadData];
[self takeTableContentsUp];
}
Am I missing something about fetch result controller? Why is this problem happening and how can I fix it?
Thank you!
EDIT: If I remove "Chat" entity in saving message, just save the message everyting is ok for chat panel. Thus the problem is multiple entities interacted with each other.
How should i edit and save 2 entities to core data, and fetch without problem?

Core Data and NSFRC showing entries but not persisting through every launch and a Key-Value Coding Error

I am building up a very simple application, allowing users to browse leaflets and videos within the application on a particular topic. One of the features I'm bringing is being able to mark a leaflet or video as a favourite.
The application is UITabBar with 5 tabs and every tab being represented by a UITableViewController. When the user taps to hold on a cell in a tab, it marks it as "starred" and with the use of Core Data and NSFetchedResultsController, the idea is for that entry to appear in the Starred tab.
This is my simple Core Data model:
So when the user taps and holds a cell in any one of the 4 tabs, this is the code I run:
- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
switch (index) {
case 0:
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
CustomLeafletVideoTableViewCell *cell = (CustomLeafletVideoTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
NSString *cellTitle = cell.customCellLabel.text;
[self moreButtonPressed:cellTitle];
[cell hideUtilityButtonsAnimated:YES];
break;
}
default:
break;
}
}
- (void)cellPressed:(NSString *)passedString
{
NSManagedObjectContext *context = [self managedObjectContext];
Item *item = [NSEntityDescription insertNewObjectForEntityForName:#"Item" inManagedObjectContext:context];
Videos *videos = [NSEntityDescription insertNewObjectForEntityForName:#"Videos" inManagedObjectContext:context];
videos.title = passedString;
item.video = videos;
NSLog(#"Passed String = %#", videos.title);
}
I have created a FavouritesTableViewController class and here's the main code:
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)])
{
context = [delegate managedObjectContext];
}
return context;
}
- (NSFetchedResultsController *)fetchedResultsController
{
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
if (_fetchedResultsController != nil)
{
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Videos" inManagedObjectContext:managedObjectContext];
fetchRequest.entity = entity;
NSPredicate *d = [NSPredicate predicateWithFormat:#"items.video.#count !=0"];
[fetchRequest setPredicate:d];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:NO];
fetchRequest.sortDescriptors = [NSArray arrayWithObject:sort];
fetchRequest.fetchBatchSize = 20;
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:nil];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSError *error;
if (![[self fetchedResultsController] performFetch:&error])
{
//exit(-1);
}
self.favouritesTableView.dataSource = self;
self.favouritesTableView.delegate = self;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.favouritesTableView reloadData];
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id sectionInfo = [[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
#pragma mark Cell Configuration
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
CustomLeafletVideoTableViewCell *customCell = (CustomLeafletVideoTableViewCell *)cell;
Videos *videos = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSLog(#"What is the video . title %#", videos.title);
customCell.customCellLabel.text = videos.title;
//
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"FavouritesCell";
CustomLeafletVideoTableViewCell *cell = (CustomLeafletVideoTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
#pragma mark NSFetchedResultsControllerDelegate Methods
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
// The boiler plate code for the NSFetchedResultsControllerDelegate
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
default:
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
[self.tableView endUpdates];
}
Issues
My issues seem to stem from the NSFetchedResultsController. In that method, if I leave it as it is with the predicate, when I tap to hold the cell on the other tab, the app crashes with:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<Videos 0x7ffb48d0b910> valueForUndefinedKey:]: the entity Videos is not key value coding-compliant for the key "#count".'
If I remove the predicate line:
// NSPredicate *d = [NSPredicate predicateWithFormat:#"items.video.#count !=0"];
// [fetchRequest setPredicate:d];
when I tap to hold a cell, it marks it as favourite and then when I go to the favourites tab, the entry is there. However, if I launch the app again, the entries in the Favourites tab have gone.
I'm not quite sure what's going on here. Essentially, the Favourites tab is a place for storing the starred items from the user from the other tabs. Do I need a predicate and if I don't, why is the data not persisting through each launch?
The app was set up with Core Data selected, so the AppDelegate has been set up appropriately.
Any guidance on this would be really appreciated.
The video property of Item is a to-one relationship. Basically it's a pointer to an object (or nil). You can't count it, it's not a collection of objects.
So your key path items.video.#count and in particular the video.#count doesn't make sense, hence the crash.
If you want to check if there is a video for a given Item, use #"items.video != nil".
Also you should probably follow conventions and use singular for your objects names (Leaflet and Video) and singular for to-one relationships (item instead of items).

how to transfer my data base information (core data) to a tableview using fecthedResultsController?

I have been trying for several days to transfer my data base information (core data) to a tableview using fecthedResultsController but nothing seams to work!
my entity name is "password" and ther are 4 strings attributes.
i'm trying to make a table that its sections are defined by an attribute called "type".
right now, that is how my code on my mainViewController.m looks like:
-(NSFetchedResultsController*)fecthedResultsController
{
if(fecthedResultsController!=nil)
return fecthedResultsController;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Password" inManagedObjectContext:[self manageObjectContext]];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"type" ascending:YES];
//here is the problam
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
fecthedResultsController=[[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:[self manageObjectContext] sectionNameKeyPath:#"type" cacheName:nil];
fecthedResultsController.delegate=self;
NSLog(#"fecthedResultsController");
return fecthedResultsController;
}
-(void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tblMain beginUpdates];
}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tblMain endUpdates];
}
-(void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView*tableview=self.tblMain;
NSLog(#"didChangeObject");
switch (type) {
case NSFetchedResultsChangeInsert:
[tableview insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:[tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:{
Password*p=[self.fecthedResultsController objectAtIndexPath:indexPath];
UITableViewCell*cell=[tableview cellForRowAtIndexPath:indexPath];
cell.textLabel.text=p.userName;
cell.detailTextLabel.text=p.password;
// cell.imageView.image=[UIImage imageWithData: p.photodata];
}
break;
case NSFetchedResultsChangeMove:
[tableview deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[tableview insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
default:
break; }
}
-(void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger) sectionIndex forChangeType: (NSFetchedResultsChangeType)type
{
NSLog(#"didChangeSection");
switch (type) {
case NSFetchedResultsChangeInsert:
[self.tblMain insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:[self.tblMain deleteSections:[NSIndexSet
indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
default:
break;
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return [[self.fecthedResultsController sections]count];
// NSLog(#"%i",[[self.fecthedResultsController sections]count]);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id<NSFetchedResultsSectionInfo>secInfo=[[self.fecthedResultsController sections]objectAtIndex:section];
return [secInfo numberOfObjects];
NSLog(#"numberOfRowsInSection");
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Configure the cell...
Password*p=[self.fecthedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text=p.userName;
// if(p.photodata!=nil)
// cell.imageView.image=[UIImage imageWithData: p.photodata];
return cell;
}
-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:
(NSInteger)section
{
return [[[self.fecthedResultsController sections]objectAtIndex:section]name];
NSLog(#"cellForRowAtIndexPath");
}
the error that the log gives me is:
2013-04-30 12:31:04.326 passwordCore[33586:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Password''
*** First throw call stack: (0x1fac012 0x13e9e7e 0x10eff57 0x2d18 0x3832 0x20383e 0x204554 0xba793 0xc9937 0xc92dc 0xccdd6 0xd1a7e 0x6e2dd 0x13fd6b0 0x25a8fc0 0x259d33c 0x259d150 0x251b0bc 0x251c227 0x25beb50 0x1c39f 0x1ce81 0x2dcb5 0x2ebeb 0x20698 0x1f07df9 0x1f07ad0 0x1f21bf5 0x1f21962 0x1f52bb6 0x1f51f44 0x1f51e1b 0x1c17a 0x1dffc 0x1d3d 0x1c65) libc++abi.dylib: terminate called throwing an exception (lldb)
and it points to the 6th line of my code.
i dont understand if the problam is the manageObjectContext or the entityForName:#"Password"
i was told that this is a esay way to deal with tableview and data..
Right now I'm just frustrated...
i will love for some help.
You should get hold of a valid, main thread based NSManagedObjectContext. in a default core data project (the one provided by the Apple template) the main managed object context is accessible via the AppDelegate.
You should either pass your context from view controller to view controller, or just ask for it from the AppDelegate like so:
self.managedObjectContext = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).managedObjectContext;

NSFetchedResultsController delegate fires methods only on first app launch

Sorry for my terrible english.
I have big problem in my iOS app. Application has big database which is managed by Core Data. And I have many TableView Controllers for displaying this data. Any change in database should be shown in tableview. It can be reached by implementing NSFetchedResultsController delegate protocol. All realization are very simple like in books. If application starts in simulator first time and I add new entries in some tables next delegate methods are successfully fired:
– controllerWillChangeContent:
– controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:
– controllerDidChangeContent:
After stop debugging and start application again none of listed methods are fired.
They calls only after [managedObjectContext save] operation will perform.
Have you any ideas why this happens?
Source code:
//IssueProfileViewController.h class implements NSFetchedResultController delegate methods
- (NSFetchedResultsController*)fetchedResultsController{
if (_fetchedResultsController == nil) {
NSManagedObjectContext *managedObjectContext = self.issue.managedObjectContext;
NSFetchRequest *aFetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"IssueHistoryItem" inManagedObjectContext:managedObjectContext];
[aFetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"created" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
//NSPredicate *predicate = [[NSPredicate predicateWithFormat:#"issue == %# && isComment == NO", self.issue] retain];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"issue == %# && isComment == NO", self.issue];
[aFetchRequest setSortDescriptors:sortDescriptors];
[aFetchRequest setPredicate:predicate];
NSFetchedResultsController *aFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:aFetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[aFetchRequest release];
//[predicate release];
[sortDescriptors release];
[sortDescriptor release];
_fetchedResultsController = aFetchedResultsController;
_fetchedResultsController.delegate = self;
}
return _fetchedResultsController;
}
-(void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
}
-(void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}
-(void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
NSArray *paths;
// NSIndexSet *section = [NSIndexSet indexSetWithIndex:[newIndexPath section]];
NSIndexPath *cellContentIndexPath;
switch (type) {
case NSFetchedResultsChangeInsert:
// paths = [NSArray arrayWithObject:newIndexPath];
if (![anObject isKindOfClass:[ChangeIssueDimensionValueHistoryItem class]]) {
cellContentIndexPath = [NSIndexPath indexPathForRow:newIndexPath.row inSection:newIndexPath.section];
paths = [NSArray arrayWithObject:cellContentIndexPath];
[self.tableView insertRowsAtIndexPaths:paths
withRowAnimation:UITableViewRowAnimationFade];
[self sendMessageAboutObjectsCountChanged];
}
break;
case NSFetchedResultsChangeDelete:
paths = [NSArray arrayWithObject:indexPath];
[self.tableView deleteRowsAtIndexPaths:paths
withRowAnimation:UITableViewRowAnimationFade];
[self sendMessageAboutObjectsCountChanged];
break;
case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[self.tableView cellForRowAtIndexPath:indexPath]
withIssueHistoryItem:[self.fetchedResultsController objectAtIndexPath:indexPath]];
break;
default:
break;
}
}
That seems to be the proper way that the NSFetchedResultsController performs--responding to changes at the model layer (i.e. [managedObjectContext save]).
In the documentation: https://developer.apple.com/library/ios/#documentation/CoreData/Reference/NSFetchedResultsController_Class/Reference/Reference.html under 'Responding to Changes' it states that the controller will not show changes until the managed object's context has received a processPendingChanges message. That message can be triggered manually, also.

Resources