load UICollectionView from core data - iphone

I'm developing an iOS app and at a certain point I store images draw by the user in Core Data.
Now I would like to load all the recorded images in a UICollectionView so the user could select one and share it on social networks.
Everything in my app works except this last part.
I followed all sorts of tutorials on the net but all examples I could find on UICollectionView were using images from Flickr or similar websites.
Here is my code at this point:
#import "LibraryViewController.h" (The name of the class we're in)
#import "SocialViewController.h"
#import "CollectionViewCell.h"
static NSString *cellIdentifier = #"MemeCell";
#implementation LibraryViewController {
NSMutableArray *_objectChanges;
NSMutableArray *_sectionChanges;
}
#pragma mark - View Controller LifeCycle
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
_objectChanges = [NSMutableArray array];
_sectionChanges = [NSMutableArray array];
self.title = #"Meme collection";
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"share"]) {
NSIndexPath *indexPath = [[self.collectionView indexPathsForSelectedItems] lastObject];
NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
SocialViewController *destViewController = segue.destinationViewController;
[destViewController setDetailItem:object];
}
}
#pragma mark - UICollectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
return [sectionInfo numberOfObjects];
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
CollectionViewCell *cell = (CollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier
forIndexPath:indexPath];
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
[cell setImage:[UIImage imageWithData:[object valueForKey:#"image"]]];
return cell;
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Meme" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Master"];
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 %#, %#", error, [error userInfo]);
abort();
}
return _fetchedResultsController;
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
NSMutableDictionary *change = [NSMutableDictionary new];
switch(type) {
case NSFetchedResultsChangeInsert:
change[#(type)] = #(sectionIndex);
break;
case NSFetchedResultsChangeDelete:
change[#(type)] = #(sectionIndex);
break;
}
[_sectionChanges addObject:change];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
NSMutableDictionary *change = [NSMutableDictionary new];
switch(type)
{
case NSFetchedResultsChangeInsert:
change[#(type)] = newIndexPath;
break;
case NSFetchedResultsChangeDelete:
change[#(type)] = indexPath;
break;
case NSFetchedResultsChangeUpdate:
change[#(type)] = indexPath;
break;
case NSFetchedResultsChangeMove:
change[#(type)] = #[indexPath, newIndexPath];
break;
}
[_objectChanges addObject:change];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if ([_sectionChanges count] > 0)
{
[self.collectionView performBatchUpdates:^{
for (NSDictionary *change in _sectionChanges)
{
[change enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, id obj, BOOL *stop) {
NSFetchedResultsChangeType type = [key unsignedIntegerValue];
switch (type)
{
case NSFetchedResultsChangeInsert:
[self.collectionView insertSections:[NSIndexSet indexSetWithIndex:[obj unsignedIntegerValue]]];
break;
case NSFetchedResultsChangeDelete:
[self.collectionView deleteSections:[NSIndexSet indexSetWithIndex:[obj unsignedIntegerValue]]];
break;
case NSFetchedResultsChangeUpdate:
[self.collectionView reloadSections:[NSIndexSet indexSetWithIndex:[obj unsignedIntegerValue]]];
break;
}
}];
}
} completion:nil];
}
if ([_objectChanges count] > 0 && [_sectionChanges count] == 0)
{
[self.collectionView performBatchUpdates:^{
for (NSDictionary *change in _objectChanges)
{
[change enumerateKeysAndObjectsUsingBlock:^(NSNumber *key, id obj, BOOL *stop) {
NSFetchedResultsChangeType type = [key unsignedIntegerValue];
switch (type)
{
case NSFetchedResultsChangeInsert:
[self.collectionView insertItemsAtIndexPaths:#[obj]];
break;
case NSFetchedResultsChangeDelete:
[self.collectionView deleteItemsAtIndexPaths:#[obj]];
break;
case NSFetchedResultsChangeUpdate:
[self.collectionView reloadItemsAtIndexPaths:#[obj]];
break;
case NSFetchedResultsChangeMove:
[self.collectionView moveItemAtIndexPath:obj[0] toIndexPath:obj[1]];
break;
}
}];
}
} completion:nil];
}
[_sectionChanges removeAllObjects];
[_objectChanges removeAllObjects];
}
#end
When I run and try to access this ViewController, the app crashes with this error message:
2013-07-25 23:08:11.832 MemeGen[87259:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSManagedObjectContext parameter searching for entity name 'Meme''
* First throw call stack:
and it points to this line of code:
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Meme" inManagedObjectContext:self.managedObjectContext];
Obviously the self.managedObjectContext is nil.
How should I assign it? And when the user launches the application for the first time and the core data is empty, how should I manage it ? Forbidding its access as long as there are no images?
Otherwise, I know how to store the draw images on the file system. If someone knew a way to load it in the UICollectionView it could also be a solution I could accept.

I would not recommend storing images in core data unless you are using the external storage functionality. Large binary objects are rarely something you want to store inside something like core data. You can, of course, store filesystem paths or URLs on core data objects that point to images on the filesystem.
To use Core Data with a UICollectionView, take a look at NSFetchedResultsController.
Here's an example of using the two together to get you started.

You will want to get a reference to your ManagedObjectContext. Oftentimes this gets created in your application delegate. In which case you will want something like this -
NSManagedObjectContext *aManagedObjectContext = ((AppDelegate *)[UIApplication sharedApplication].delegate).managedObjectContext;
If you want you can do this in your viewDidLoad and assign it to self.managedObjectContext.

Related

NSFetchedResultsController not updating?

When my user sees a picture, she can like it by pressing a button. The following code is run:
- (void)feedback:(Item *)item isLiked:(bool)liked {
// Update the item with the new score asynchornously
NSManagedObjectID *itemId = item.objectID;
dispatch_async(dispatch_get_main_queue(), ^{
// Create a new managed object context and set its persistent store coordinator
// Note that this **must** be done here because this context belongs to another thread
AppDelegate *theDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *localContext = [[NSManagedObjectContext alloc] init];
[localContext setPersistentStoreCoordinator:[theDelegate persistentStoreCoordinator]];
Item *localItem = (Item *)[localContext objectWithID:itemId];
localItem.liked = [NSNumber numberWithBool:liked];
localItem.updated_at = [NSDate date];
NSError *error;
if (![localContext save:&error]) {
NSLog(#"Error saving: %#", [error localizedDescription]);
}
});
In my app, LikedViewController shows the images that the user has liked. LikedVC consists of a UITableViewController hooked up to an NSFetchedResultsController.
LikedVC:
- (void)viewDidLoad
{
[super viewDidLoad];
// NSFetchedResultsController
NSManagedObjectContext *moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
_fetchedResultsController = \
[[NSFetchedResultsController alloc] initWithFetchRequest:[self.delegate getFetchRequest]
managedObjectContext:moc
sectionNameKeyPath:nil
cacheName:nil]; // TODO investigate whether we should bother with cache
_fetchedResultsController.delegate = self;
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
// Bottom loading bar
self.tableView.tableFooterView = self.footerView;
self.footerActivityIndicator.hidesWhenStopped = true;
// ActivityIndicator
self.activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
self.activityIndicator.color = [UIColor blackColor];
[self.tableView addSubview:self.activityIndicator];
self.activityIndicator.hidesWhenStopped = true;
// FIXME Unable to center it inside the tableView properly
self.activityIndicator.center = CGPointMake(self.tableView.center.x, self.tableView.center.y - self.tabBarController.tabBar.frame.size.height);
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
// Automatically fetch when there is nothing in the UITableView
if ([self tableView:self.tableView numberOfRowsInSection:0] == 0) {
if ([self canFetch]) {
[self refill];
}
}
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
if (self.operation && self.operation.isExecuting) {
NSLog(#"Cancelling Operation: %#", self.operation);
[self.operation cancel];
self.isFetching = false;
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"FeedCell";
Item *item = [_fetchedResultsController objectAtIndexPath:indexPath];
FeedCell *cell = (FeedCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.item = item;
cell.tag = indexPath.row;
cell.customImageView.userInteractionEnabled = YES;
// NOTE Don't try to do this at the UITableViewCell level since the tap will be eaten by the UITableView/ScrollView
if (self.likeOnTap) {
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:#selector(tapped:)];
tap.numberOfTapsRequired = 1;
[cell.customImageView addGestureRecognizer:tap];
}
// Set up the buttons
[cell.likeButton addTarget:self action:#selector(liked:) forControlEvents:UIControlEventTouchUpInside];
[cell.dislikeButton addTarget:self action:#selector(disliked:) forControlEvents:UIControlEventTouchUpInside];
[cell.detailButton addTarget:self action:#selector(detailed:) forControlEvents:UIControlEventTouchUpInside];
[[SDImageCache sharedImageCache] queryDiskCacheForKey:item.image_url done:^(UIImage *image, SDImageCacheType type) {
if (image) {
[cell setCustomImage:image];
} else {
// If we have to download, make sure user is on the image for more than 0.25s before we
// try to fetch. This prevents mass downloading when the user is scrolling really fast
double delayInSeconds = 0.25;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
if ([self isIndexPathVisible:indexPath]) {
[SDWebImageDownloader.sharedDownloader
downloadImageWithURL:[NSURL URLWithString:item.image_url]
options:0
progress:^(NSUInteger receivedSize, long long expectedSize) { }
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
if (image && finished) {
[cell setCustomImage:image];
[[SDImageCache sharedImageCache] storeImage:image forKey:item.image_url];
}
}];
}
});
}
}];
// Check if we are almost at the end of the scroll. If so, start fetching.
// Doing this here is better than overriding scrollViewDidEndDragging
if (indexPath.row >= [self.tableView numberOfRowsInSection:0] - 3) {
[self refill];
}
return cell;
}
#pragma mark - Table view delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id sectionInfo = [_fetchedResultsController.sections objectAtIndex:section];
NSInteger ret = [sectionInfo numberOfObjects];
self.hasContent = (ret != 0);
return ret;
}
# pragma mark - NSFetchedResultsControllerDelegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
NSLog(#"1");
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
NSLog(#"2");
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
NSLog(#"3");
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:
[NSException raise:#"Unknown update" format:#"NSFetchedResultsChangeUpdate: invoked"];
// [self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[NSException raise:#"Unknown update" format:#"NSFetchedResultsChangeMove: invoked"];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
NSLog(#"4");
[self.tableView endUpdates];
}
(Note that I have omitted some info to keep this question short)
This is the fetchRequest of LikedVC
- (NSFetchRequest *)getFetchRequest {
NSManagedObjectContext *moc = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Item" inManagedObjectContext:moc];
[request setPredicate:[NSPredicate predicateWithFormat:#"liked == %d OR origin == %d", 1, OriginsLike]];
[request setEntity:entity];
[request setResultType:NSManagedObjectResultType];
[request setFetchBatchSize:10];
NSSortDescriptor *d = [[NSSortDescriptor alloc] initWithKey:#"updated_at" ascending:NO selector:nil];
[request setSortDescriptors:[NSArray arrayWithObject:d]];
return request;
}
I am seeing a bug where the user has liked a item, but then when the user switches over to LikedVC the item is not shown anywhere.
I added NSLog(#"1"), NSLog(#"2"), ... in the tableView's controllerDidChangeContent, controllerWillChangeContent, etc methods. I do not see "1", "2", .. being logged at all.
Why is my NSFetchedResultsController not working?
Direct Answer
The direct answer to your question is you need to observe NSManagedObjectContextDidSaveNotification and merge the changes from your temporary context into the main context that the NSFetchedResultsController is observing. It's best to do this in whatever object owns your main context. Looks like you're using your app delegate.
You merged the data as follows:
- (void)managedObjectContextDidSave:(NSNotification *)notification
{
// if the notification is on a background thread, forward it to the main thread
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:#selector(managedObjectContextDidSave:) withObject:notification];
return;
}
// if a context other than the main context has saved, merge the changes
if (notification.object != self.managedObjectContext) {
[self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
}
}
Your code seems suspect
All of your logic happens on the main queue so you don't really need another context at all. There's also no real benefit to using dispatch_async on the main queue in this case. If you keep everything on the main thread just create and save the new object directly into the main context. If you really do want things to be asynchronous, the use dispatch_async to dispatch the block to a background queue and then you would need a new context (as you have implemented) for the background thread.

Uncaught exception error! Simple document app

Removed the colon which wasn't supposed to be there since my selector doesn't have one. It fixed it, then this problem occurred:
2012-06-02 22:33:10.083 TinyPix[10433:fb03] load OK
2012-06-02 22:33:10.084 TinyPix[10433:fb03] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<BIDTinyPixDocument 0x6e665a0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key timeStamp.'
*** First throw call stack:
(0x16b0022 0x1841cd6 0x16afee1 0x9c8efe 0x937831 0x936c99 0x5f47 0x5e77 0x93af30 0x93aedb 0x59ed 0x4546e3 0x40778d9 0x4078509 0x15e7803 0x15e6d84 0x15e6c9b 0x15997d8 0x159988a 0x1b626 0x2a5d 0x29c5)
terminate called throwing an exception
Here's my detail file: I'm getting a SIGABRT error on the self.detailDescriptionLabel.text line. Don't know what's going on.
#import "BIDDetailViewController.h"
#interface BIDDetailViewController ()
- (void)configureView;
#end
#implementation BIDDetailViewController
#synthesize detailItem = _detailItem;
#synthesize detailDescriptionLabel = _detailDescriptionLabel;
#pragma mark - Managing the detail item
- (void)setDetailItem:(id)newDetailItem
{
if (_detailItem != newDetailItem) {
_detailItem = newDetailItem;
// Update the view.
[self configureView];
}
}
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
self.detailDescriptionLabel.text = [[self.detailItem valueForKey:#"timeStamp"] description];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self configureView];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
self.detailDescriptionLabel = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#end
Here's my file:
#import "BIDMasterViewController.h"
#import "BIDTinyPixDocument.h"
#import "BIDDetailViewController.h"
#interface BIDMasterViewController () <UIAlertViewDelegate>
#property (strong, nonatomic) NSArray *documentFilenames;
#property (strong, nonatomic) BIDTinyPixDocument *chosenDocument;
-(NSURL *)urlForFilename:(NSString *)filename;
-(void)reloadFiles;
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation BIDMasterViewController
#synthesize colorControl;
#synthesize documentFilenames;
#synthesize chosenDocument;
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
- (void)awakeFromNib
{
[super awakeFromNib];
}
-(void)viewWillAppear:(BOOL)animated;
{
[super viewWillAppear:animated];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSInteger selectedColorIndex = [prefs integerForKey:#"selectedColorIndex"];
self.colorControl.selectedSegmentIndex = selectedColorIndex;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
[self reloadFiles];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)insertNewObject
{
// get the name
UIAlertView *alert =
[[UIAlertView alloc] initWithTitle:#"Filename"
message:#"Enter a name for your new TinyPix document."
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Create", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
}
#pragma mark - Table View
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error = nil;
if (![context save:&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 %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// The table view should not be re-orderable.
return NO;
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:self.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:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects: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:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Master"];
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 %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (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:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (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:[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;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[object valueForKey:#"timeStamp"] description];
}
-(NSURL *)urlForFilename:(NSString *)filename {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentDirectory stringByAppendingPathComponent:filename];
NSURL *url = [NSURL fileURLWithPath:filePath];
return url;
}
-(void)reloadFiles {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *dirError;
NSArray *files = [fm contentsOfDirectoryAtPath:path error:&dirError];
if (!files) {
NSLog(#"Encountered error while trying to list files in directory %#: %#", path, dirError);
}
NSLog(#"found files: %#", files);
files = [files sortedArrayUsingComparator:^NSComparisonResult(id filename1, id filename2) {
NSDictionary *attr1 = [fm attributesOfItemAtPath:[path stringByAppendingPathComponent:filename1]
error:nil];
NSDictionary *attr2 = [fm attributesOfItemAtPath:[path stringByAppendingPathComponent:filename2]
error:nil];
return [[attr2 objectForKey:NSFileCreationDate] compare:[attr1 objectForKey:NSFileCreationDate]];
}];
self.documentFilenames = files;
[self.tableView reloadData];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.documentFilenames count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"FileCell"];
NSString *path = [self.documentFilenames objectAtIndex:indexPath.row];
cell.textLabel.text = path.lastPathComponent.stringByDeletingPathExtension;
return cell;
}
-(IBAction)chooseColor:(id)sender {
NSInteger selectedColorIndex = [(UISegmentedControl *)sender selectedSegmentIndex];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setInteger:selectedColorIndex forKey:#"selectedColorIndex"];
}
-(void)alertView:(UIAlertView *)alertView
didDismissWithButtonIndex:(NSInteger)buttonIndex {
if (buttonIndex == 1) {
NSString *filename = [NSString stringWithFormat:#"%#.tinypix",
[alertView textFieldAtIndex:0].text];
NSURL *saveUrl = [self urlForFilename:filename];
self.chosenDocument = [[BIDTinyPixDocument alloc] initWithFileURL:saveUrl];
[chosenDocument saveToURL:saveUrl
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success) {
if (success) {
NSLog(#"save OK");
[self reloadFiles];
[self performSegueWithIdentifier:#"masterToDetail"
sender:self];
} else {
NSLog(#"failed to save!");
}
}];
}
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if (sender == self) {
// if sender == self, a new document has just been created,
// and chosenDocument is already set.
UIViewController *destination = segue.destinationViewController;
if ([destination respondsToSelector:#selector(setDetailItem:)]) {
[destination setValue:self.chosenDocument forKey:#"detailItem"];
}
}else {
// find the chose document from the tableview
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSString *filename = [documentFilenames objectAtIndex:indexPath.row];
NSURL *docUrl = [self urlForFilename:filename];
self.chosenDocument = [[BIDTinyPixDocument alloc] initWithFileURL:docUrl];
[self.chosenDocument openWithCompletionHandler:^(BOOL success) {
if (success) {
NSLog(#"load OK");
UIViewController *destination = segue.destinationViewController;
if ([destination respondsToSelector:#selector(setDetailItem:)]) {
[destination setValue:self.chosenDocument forKey:#"detailItem"];
}
}else {
NSLog(#"failed to load!");
}
}];
}
}
#end
You specify the selector as insertNewObject: and the colon on the end says that it takes one parameter. The insertNewObject method you implemented takes no parameters and, to Objective-C, that makes it a different thing and it can't find the one parameter method.
You should change your implementation to - (IBAction)insertNewObject:(id)sender {...} to match #selector(insertNewObject:).

Sort button for tableview in navigation app

I'm currently creating an application to rank teams based on different criteria, and I would like to give users the option to sort the teams in a table view based on those different criteria. I use core data in my app to store my teams, and am using a navigation-based template that starts by showing the user a table view with the option to click on each cell to edit a team. An example of what I want to do is how the Errands app lets you sort your tasks by Due date, priority, alphabetical, and manual.
I tried creating buttons that called a method to change, the sortDescriptor key, but I have to recreated the fetchedResultsController every time for this to update (i.e. don't check if the fetchedResultsController_ ! = nil), and that seems to copy the cell that is changing positions into the new position rather than moving it there.
How should I go about coding a sort button that lets the user change the criteria by which the table is sorted and correctly update the table? I've read a lot of posts concerning the fetchResultsController and NSSortDescriptors, but the solutions seem to be a one-time deal.
I could really use some help, or reference to a tutorial that shows how to do this.
Here is my RootViewController.m:
#import "RootViewController.h"
#import "TeamViewController.h"
#interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation RootViewController
#synthesize fetchedResultsController=fetchedResultsController_;
#synthesize managedObjectContext=managedObjectContext_;
#synthesize sortParam;
//#synthesize sortDescriptors;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
NSLog(#"viewDidLoad called");
sortParam = #"totalRank";
[super viewDidLoad];
self.title = #"Title";
// Set up the edit and add buttons.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showTeamView)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
UIBarButtonItem* button1 = [[[UIBarButtonItem alloc] initWithTitle:#"Rank" style:UIBarButtonItemStyleBordered target:self action:#selector(reSort1:)] autorelease];
UIBarButtonItem* button2 = [[[UIBarButtonItem alloc] initWithTitle:#"Name" style:UIBarButtonItemStyleBordered target:self action:#selector(reSort2:)] autorelease];
[self setToolbarItems:[NSArray arrayWithObjects:button1, button2, nil]];
}
-(void)showTeamView {
NSLog(#"showTeamView called");
TeamViewController *teamViewController = [[TeamViewController alloc] initWithRootController:self team:nil];
[self presentModalViewController:teamViewController animated:YES];
[teamViewController release];
}
// Implement viewWillAppear: to do additional setup before the view is presented.
- (void)viewWillAppear:(BOOL)animated {
NSLog(#"viewWillAppear called");
// sortParam = #"totalRank";
[super viewWillAppear:animated];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSLog(#"configureCell:atIndexPath called");
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *textLabelText = [NSString stringWithFormat:#"%# - %#", [[managedObject valueForKey:#"teamName"]description], [[managedObject valueForKey:#"teamNumber"]description]];
// NSLog(textLabelText);
cell.textLabel.text = textLabelText;//[[managedObject valueForKey:#"teamName"] description];
cell.detailTextLabel.text = [[managedObject valueForKey:#"totalRank"] description];
// cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
}
- (void)reSort1:(id)sender {
NSLog(#"reSort1 called by: %#", sender);
sortParam = #"totalRank";
[self.tableView reloadData];
[self viewDidLoad];
}
- (void)reSort2:(id)sender {
NSLog(#"resort2 called by %#", sender);
sortParam = #"teamName";
[self.tableView reloadData];
[self viewDidLoad];
}
#pragma mark -
#pragma mark Add a new object
-(void)insertTeamWithName:(NSString *)teamName teamNumber:(NSString *)teamNumber noteField:(NSString *)noteField driveTrain:(NSString *)driveTrain autoRank:(NSNumber *)autoRank offenseRank:(NSNumber *)offenseRank defenseRank:(NSNumber *)defenseRank speedRank:(NSNumber *)speedRank shooterRank:(NSNumber *)shooterRank totalRank:(NSNumber *)totalRank{
// Create a new instance of the entity
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// Configure the team
[newManagedObject setValue:teamName forKey:#"teamName"];
[newManagedObject setValue:teamNumber forKey:#"teamNumber"]; //new
[newManagedObject setValue:noteField forKey:#"noteField"];
[newManagedObject setValue:autoRank forKey:#"autoRank"];
[newManagedObject setValue:driveTrain forKey:#"driveTrain"];
[newManagedObject setValue:offenseRank forKey:#"offenseRank"];
[newManagedObject setValue:defenseRank forKey:#"defenseRank"];
[newManagedObject setValue:speedRank forKey:#"speedRank"];
[newManagedObject setValue:shooterRank forKey:#"shooterRank"];
/* [newManagedObject setValue:armRank forKey:#"armRank"];
[newManagedObject setValue:speedRank forKey:#"speedRank"]; */
[newManagedObject setValue:totalRank forKey:#"totalRank"];
[self saveContext];
NSLog(#"insertTeamWithNameCalled");
}
- (void)saveContext {
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
// Save the context.
NSError *error = nil;
if (![context save:&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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error in saveContext %#, %#", error, [error userInfo]);
// abort();
}
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
// Prevent new objects being added when in editing mode.
[super setEditing:(BOOL)editing animated:(BOOL)animated];
self.navigationItem.rightBarButtonItem.enabled = !editing;
}
#pragma mark -
#pragma mark Table view data source
/*
- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
}
*/
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"tableView:cellForRowAtIndexPath called");
static NSString *CellIdentifier = #"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the managed object for the given index path
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
// Save the context.
[self saveContext];
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// The table view should not be re-orderable.
return NO;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *team = [[self fetchedResultsController] objectAtIndexPath:indexPath];
TeamViewController *teamViewController = [[TeamViewController alloc] initWithRootController:self team:team];
[self presentModalViewController:teamViewController animated:YES];
[teamViewController release];
}
#pragma mark -
#pragma mark Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController {
NSLog(#"fetchResultsController called");
/*
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:#"Team" inManagedObjectContext:self.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:sortParam ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
NSLog(#"sortParam == %#", sortParam);
// 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:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error in fetchedResultsController %#, %#", error, [error userInfo]);
// abort();
}
return fetchedResultsController_;
}
#pragma mark -
#pragma mark Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
NSLog(#"controllerWillChangeContent called");
[self.tableView beginUpdates];
}
- (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:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
NSLog(#"controller:didChangeObject called");
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;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
NSLog(#"controllerDidChangeContent called");
[self.tableView endUpdates];
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[fetchedResultsController_ release];
[managedObjectContext_ release];
// [sortParam release];
[super dealloc];
}
#end

What Does This NSZombie Error Message Mean?

I turned zombies on because I was getting some crashes. Now I' getting this error in console. Does anyone know what it means?
*** -[RoutineDayTableViewController retain]: message sent to deallocated instance 0x7464150
#implementation RoutineDayTableViewController
#synthesize fetchedResultsController;
#synthesize exerciseChooserView;
#synthesize routineTableView;
#synthesize managedObjectContext;
#synthesize selectedExercise;
#synthesize theSelectedRoutine;
- (void)dealloc
{
NSLog(#"dealloc");
[fetchedResultsController release];
[selectedExercise release];
[managedObjectContext release];
[exerciseChooserView release];
[routineTableView release];
[theSelectedRoutine release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.routineTableView.delegate = self;
if (managedObjectContext == nil)
{
managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
[managedObjectContext retain];
}
}
- (void)viewDidUnload
{
NSLog(#"viewDidUnload");
[super viewDidUnload];
self.exerciseChooserView = nil;
self.routineTableView = nil;
self.fetchedResultsController = nil;
}
#pragma mark - Exercise Editing
-(IBAction)exerciseChooser
{
RoutineExerciseChooserViewController *routineExerciseChooserViewController = [[[RoutineExerciseChooserViewController alloc] init] autorelease];
[self.navigationController pushViewController:routineExerciseChooserViewController animated:YES];
}
-(void)addExercise
{
if (managedObjectContext == nil)
{
managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
[managedObjectContext retain];
}
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(exerciseChooser)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
NSError *error = nil;
Exercise *exercise = (Exercise *)[NSEntityDescription insertNewObjectForEntityForName:#"Exercise" inManagedObjectContext:managedObjectContext];
exercise.name = self.selectedExercise;
NSLog(#"addExercise theSelectedRoutine: %#", theSelectedRoutine);
[self.theSelectedRoutine addRoutineToExercisesObject:exercise];
if (![fetchedResultsController.managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(#"%#", error);
NSLog(#"addExercise theSelectedRoutine: %#", theSelectedRoutine);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [routineTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
Exercise *tempExercise = (Exercise *)[fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = tempExercise.name;
return cell;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete the managed object for the given index path
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSLog(#"fetched results : \n%#\n",[self.fetchedResultsController fetchedObjects]);
// Commit the change.
NSError *error = nil;
// Update the array and table view.
if (![fetchedResultsController.managedObjectContext save:&error])
{
// Handle the error.
}
//[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[managedObject valueForKey:#"name"] description];
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
[routineTableView deselectRowAtIndexPath:indexPath animated:YES];
DetailViewController *detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil)
{
return fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Exercise" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSLog(#"fetchedResultsController theSelectedRoutine: %#",theSelectedRoutine);
[fetchRequest setPredicate:[NSPredicate predicateWithFormat: #"ANY exerciseToRoutine == %#", theSelectedRoutine]];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
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:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
}
#pragma mark - Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.routineTableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.routineTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.routineTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
UITableView *tableView = self.routineTableView;
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;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.routineTableView endUpdates];
}
#end
Update, this method is in another viewController. Could this be causing the problem?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
NSString *selectedRow = [[self.exerciseArray objectAtIndex:indexPath.row]objectForKey:#"exerciseName"];
NSLog(#"Row Selected: %#", selectedRow);
RoutineDayTableViewController *routineDayTableViewController=[self.navigationController.viewControllers objectAtIndex:([self.navigationController.viewControllers count] -3)];
routineDayTableViewController.selectedExercise = selectedRow;
[routineDayTableViewController addExercise];
[routineDayTableViewController release];
[self dismissView];
}
and here is another method in yet another viewController that access this class:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
RoutineDayTableViewController *detailViewController = [[RoutineDayTableViewController alloc] initWithNibName:#"RoutineDayTableViewController" bundle:nil];
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
detailViewController.title = [[managedObject valueForKey:#"name"] description];
detailViewController.theSelectedRoutine = [__fetchedResultsController objectAtIndexPath: indexPath];
NSLog(#"detailViewController.theSelectedRoutine:%#",detailViewController.theSelectedRoutine);
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
The error message means that you are sending a message to an object whose retain count went to zero and was subsequently deallocated. Based on your code snippet, I think your problem is this code -
RoutineDayTableViewController *routineDayTableViewController=[self.navigationController.viewControllers objectAtIndex:([self.navigationController.viewControllers count] -3)];
routineDayTableViewController.selectedExercise = selectedRow;
[routineDayTableViewController addExercise];
[routineDayTableViewController release];
The release call here looks suspicious. You are releasing something you haven't alloced here.
Have you run static analyzer on your code? It is helpful in detecting bugs of this kind.
The instance of the class RoutineDayTableViewController is the problem, so it's not likely in the code you posted here.
Check the code where you use this class.
It may help you to build using the Analyse option, this often detects the problem.
There are some place where the instance of RoutineDayTableViewController class is release and after that you are trying to access it.
If you want to check , Please don't release that object and try to run.

Why Can't I delete the bottom row of my UITableView?

When the user presses Edit, my UITableView adds an insert row at the top (with a green plus), and puts all the other rows into delete mode (red minus). Alternatively, the user can swipe-to-delete without pressing the edit button. I am using a couple of Ivars to keep track of whether the table is in edit mode from a swipe, or from pressing the edit button, and act accordingly (e.g. updating numberOfRowsInTableView: with the extra insert row when Edit has been pressed).
Everything works perfectly except on thing: when in Edit mode (i.e. the user has explicitly hit the edit button, and the insert row has appeared at the top), if the user tries to delete the bottom row, the next row up gets deleted instead. Deleting any other row is fine.
EDIT -- It appears to delete the row above, but if I immediately quit and reload the app, it turns out the bottom row has gone after all. So I'm guessing my UITableView is going out of sync with my NSFetchedResultsController somewhere.
Here's the code I'm using:
#import "ChecklistsViewController.h"
#import "Checklist.h"
#interface ChecklistsViewController (private)
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
- (void)addingView;
#end
#implementation ChecklistsViewController
#synthesize category, managedObjectContext, fetchedResultsController;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
editingFromSwipe = NO;
tableIsEditing = NO;
}
return self;
}
- (void)dealloc
{
[category release];
[managedObjectContext release];
[fetchedResultsController release];
[super dealloc];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
editingFromSwipe = NO;
tableIsEditing = NO;
self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.tableView.allowsSelectionDuringEditing = YES;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
int rows = [sectionInfo numberOfObjects];
if (self.editing) {
if (!editingFromSwipe && tableIsEditing) {
return rows +1;
}
return rows;
}
tableIsEditing = NO;
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
NSLog(#"Should go into if statement here! \n");
if (tableView.editing) { //
if ((indexPath.row == 0) && (!editingFromSwipe)) {
NSLog(#"Configuring Add Button Cell while editing \n");
cell.textLabel.text = #"Add New Checklist";
cell.detailTextLabel.text = nil;
}
else {
NSLog(#"Configuring other cells while editing \n");
[self configureCell:cell atIndexPath:indexPath];
}
}
else {
NSLog(#"Configuring Cell Normally While Not Editing \n");
[self configureCell:cell atIndexPath:indexPath];
}
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete the managed object for the given index path
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
int numberOfRows = [self tableView:tableView numberOfRowsInSection:indexPath.section];
int rowBeingDeleted = indexPath.row +1;
if (tableIsEditing && !editingFromSwipe && numberOfRows == rowBeingDeleted) {
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row-1 inSection:indexPath.section]]];
}
else {
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
}
// Save the context.
NSError *error = nil;
if (![context save:&error])
{
// TO DO: Fix error code.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
[self addingView];
}
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
int row = indexPath.row;
if (self.editing && row == 0) {
if (!editingFromSwipe && tableIsEditing) {
return UITableViewCellEditingStyleInsert;
}
else if (editingFromSwipe) {
return UITableViewCellEditingStyleDelete;
}
}
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
editingFromSwipe = YES;
[super tableView:tableView willBeginEditingRowAtIndexPath:indexPath];
}
- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath
{
[super tableView:tableView didEndEditingRowAtIndexPath:indexPath];
editingFromSwipe = NO;
}
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
NSArray *addRow = [NSArray arrayWithObjects:[NSIndexPath indexPathForRow:0 inSection:0], nil];
[self.tableView beginUpdates];
if (!editingFromSwipe) {
if (editing) {
tableIsEditing = YES;
[self.tableView insertRowsAtIndexPaths:addRow withRowAnimation:UITableViewRowAnimationLeft];
}
else {
[self.tableView deleteRowsAtIndexPaths:addRow withRowAnimation:UITableViewRowAnimationLeft];
}
}
[self.tableView endUpdates];
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.row != 0) {
TO DO: Code for when row is selected
}
}
#pragma mark - Data
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
Checklist *aChecklist = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = aChecklist.name;
cell.detailTextLabel.text = aChecklist.category.name;
}
- (void) addingView// :(id)sender
{
AddingViewController *viewController = [[AddingViewController alloc] initWithNibName:#"AddingViewController" bundle:nil];
viewController.delegate = self;
viewController.title = #"Add Checklist";
// Create the navigation controller and present it modally
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:viewController];
[self presentModalViewController:navigationController animated:YES];
viewController.textLabel.text = #"Enter new checklist name";
[navigationController release];
[viewController release];
}
#pragma mark - AddingViewDelegate
- (void)addingViewController:(AddingViewController *)addingViewController didAdd:(NSString *)itemAdded
{
if (itemAdded != nil) {
// Turn off editing mode.
if (self.editing) [self.navigationController setEditing:NO animated:NO];
// Add the category name to our model and table view.
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
Checklist *newChecklist = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
[category addChecklistsObject:newChecklist];
newChecklist.name = itemAdded;
// [newChecklist setDateStamp:[NSDate date]];
// Save the context.
NSError *error = nil;
if (![context save:&error])
{
TO DO: fix error code.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
[self dismissModalViewControllerAnimated:YES];
}
#pragma mark - Fetched results controller
- (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:#"Checklist" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set 4* the predicate so we only see checklists for this category.
NSPredicate *requestPredicate = [NSPredicate predicateWithFormat:#"category.name = %#", self.category.name];
[fetchRequest setPredicate:requestPredicate];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// 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:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error])
{
// TO DO: error stuff
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return fetchedResultsController;
}
#pragma mark - Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (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:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (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:[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;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
#end
You can add static cells to UITableViews that get their data from a NSFetchedResultsController. But to do this you have to adjust almost all NSIndexPaths that are used within one of the UITableViewDelegate, UITableViewDataSource or NSFetchedResultsControllerDelegate methods.
I added some helper methods that translate the indexpath of the tableview to the indexpath of the fetched resultscontroller and the other way around. Something like this could be used if you want to add a row on top:
- (NSIndexPath *)tableIndexPathFromNSFRCIndexPath:(NSIndexPath *)ip {
if (editingMode && ip.section == 0) {
NSIndexPath *newIP = [NSIndexPath indexPathForRow:ip.row+1 inSection:ip.section];
return newIP;
}
return ip;
}
- (NSIndexPath *)nsfrcIndexPathFromTableIndexPath:(NSIndexPath *)ip {
if (editingMode && ip.section == 0) {
NSIndexPath *newIP = [NSIndexPath indexPathForRow:ip.row-1 inSection:ip.section];
return newIP;
}
return ip;
}
and then you have to change every method that passes an indexpath from the table to the fetchedresultscontroller or from the frc to the table. I show you two as an example.
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
newIndexPath = [self tableIndexPathFromNSFRCIndexPath:newIndexPath];
indexPath = [self tableIndexPathFromNSFRCIndexPath:indexPath];
switch(type) {
case NSFetchedResultsChangeInsert:
[self.listTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.listTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[self.listTableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[self.listTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.listTableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[aTableView deselectRowAtIndexPath:indexPath animated:YES];
if (editingMode && indexPath.section == 0 && indexPath.row == 0) {
// Add New entry...
}
else {
indexPath = [self nsfrcIndexPathFromTableIndexPath:indexPath];
NSManagedObject *selectedObject = [self.fetchedResultsController objectAtIndexPath:indexPath]);
}
}
Your design it at fault. You shouldn't be adding rows anywhere but where they logically go in the table.
The entire point of a fetched results controller (FRC) is to synchronize the tableview with the data. The order of the rows in the table should reflect the order of managed objects in the fetchedObjects array. By inserting a row at the bottom or top and while adding an object that does not necessarily logically belong at the top or bottom of the table, are breaking that synchronization.
When you add a new managed object in addingViewController:didAdd: the FRC alerts it delegate which tries to redraw the table. You've tried to compensate for this but you really can't. All you indexes are coming off.
Instead of using a row to input new rows. Use a tableview header or footer view. That way, you can freeze the tableview, create the new object, then update the table and the new object will show up where it logical belongs in the table.
To not get the rows mixed up I would suggest putting the insert row in its own section. Since you're obviously just using one section you know that the section you send to FRC should always be 0. The code would be as simple as:
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:[NSIndexPath indexPathForRow:indexPath.row inSection:0]]];
TechZen's solution will also work, so which solution you choose is entirely about what design you prefer. TechZen's solution doesn't interfere with having multiple sections, but this solution could be modified to support multiple sections as well.