Use of undeclared identifier - Core Data - iphone

Hi i'm fairly new to xcode and i'm having trouble getting my head around why im getting this error "use of undeclared identifier" I'm basically trying to return fetched results to a table view.
// UNBSearchBooksViewController.m
#import "UNBSearchBooksViewController.h"
#import "NBAppDelegate.h"
#interface UNBSearchBooksViewController ()
#end
#implementation UNBSearchBooksViewController
#synthesize booksSearchBar;
#synthesize searchTableView;
#synthesize fetchedResultsController, managedObjectContext;
- (void)viewDidLoad
{
[super viewDidLoad];
// NSFetchRequest needed by the fetchedResultsController
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// NSSortDescriptor tells defines how to sort the fetched results
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// fetchRequest needs to know what entity to fetch
NSEntityDescription *entity = [NSEntityDescription entityForName:#"BookInfo" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [fetchedObjects count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell" ;
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell "this is where my problem is" use of undeclared identifier
BookInfo *info = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = info.title;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar
{
if (self.booksSearchBar.text !=nil)
{
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"bookName contains[cd] %#", self.booksSearchBar.text];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
else
{
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"All"];
[fetchedResultsController.fetchRequest setPredicate:predicate];
}
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error])
{
// Handle error
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
fetchedObjects = fetchedResultsController.fetchedObjects;
[booksSearchBar resignFirstResponder];
[searchTableView reloadData];
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
searchBar.showsCancelButton = YES;
}
- (void) searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
searchBar.showsCancelButton = NO;
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
#end

Your problem is that you are assigning to a specific subclass the results typed as a base class. As you stated, this is where you get the warning:
BookInfo *info = [self.fetchedResultsController objectAtIndexPath:indexPath];
'NSFetchedResultsController' returns an object of type 'id' from
- (id)objectAtIndexPath:(NSIndexPath *)indexPath
(and I suppose it could return a NSManagedObject * too), but you assign it to a BookInfo object. Since there is a mismatch here, you need to cast the return value to what you know it is:
BookInfo *info = (BookInfo *)[self.fetchedResultsController objectAtIndexPath:indexPath];
and your warning will go away.

Related

Fetching child objects belongs to parent object & put them in tableView (core-data, relationships)

I have two tableViews, the main one adds the parent object, and when you click on a parent object in the tableView, it takes you to the child tableView, I did the first part successfully, but when it comes to fetching the "RIGHT" child objects I get confused, I way I do it is that I fetch ALL child object, the using enumeration I pick the right ones and put then into a NSSet, but that doesn't work, here's the child object table view.m:
#import "MinorGoalsTableViewController.h"
#interface MinorGoalsTableViewController ()
#end
#implementation MinorGoalsTableViewController
#synthesize selectedGoal = _selectedGoal;
#synthesize fetchedResultsController = _fetchedResultsController;
#synthesize minorGoalsSet;
// init with goal (for GTVC)
- (id) initWithGoal:(Goal *)goal {
if (self = [super init]) {
_selectedGoal = goal;
}
return self;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
NSLog(#"Minor Goals in %# are: %lu", self.selectedGoal.title , (unsigned long)[self.selectedGoal.minorGoal count]);
// self.minorGoalsSet = nil;
// initializing minorGoalsSet
self.minorGoalsSet = [[NSMutableSet alloc] init];
// performing fetch
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(#"Error fetching all minor goals: %#", error);
abort();
}
// creating NSSet that will carry all selectedGoal minor goals
NSSet *minorGoals = self.selectedGoal.minorGoal;
// creating a loop to add minor goals in minorGoalsSet
// add existing minor goals in selected goal to minorGoalsSet
for (MinorGoal *minor in minorGoals) {
[minorGoalsSet addObject:minor];
}
NSLog(#"minor goals in set: %lu", (unsigned long) [minorGoalsSet count]);
NSLog(#"minor goals in set2: %lu", (unsigned long) [minorGoals count]);
// setting nav title to selected goal title
self.navigationItem.title = _selectedGoal.title;
// adding "add" button to nav
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addNewMinorGoal)];
}
- (void) viewWillDisappear:(BOOL)animated {
self.selectedGoal = nil;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.selectedGoal.minorGoal count];
// id <NSFetchedResultsSectionInfo> secInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
// return [secInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.accessoryType = UITableViewCellAccessoryNone;
// Configure the cell...
MinorGoal *minor = [self.fetchedResultsController objectAtIndexPath:indexPath];
// well see about that later
if ([minorGoalsSet containsObject:minor]) {
cell.textLabel.text = minor.title;
}
// setting cell's title to minor goal's title
// cell.textLabel.text = minor.title;
return cell;
}
pragma mark - fetched results controller method
- (NSFetchedResultsController*) fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
// creating fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"MinorGoal"
inManagedObjectContext:self.selectedGoal.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"title"
ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// setting _fetchedResultsController
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.selectedGoal.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
// performing fetch
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
NSLog(#"Error fetching minors: %#", error);
}
// returning
return _fetchedResultsController;
}
pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void) addNewMinorGoal {
// code to show UIAlertView that will add new minor goal
// creating UIAlertView
UIAlertView *addMinorGoalAlert = [[UIAlertView alloc] initWithTitle:#"Add Minor Goal" message:#"Minor Goal Title" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Save", nil];
// Adding plain textfield for minor goal title
addMinorGoalAlert.alertViewStyle = UIAlertViewStylePlainTextInput;
// showing UIAlertView
[addMinorGoalAlert show];
}
pragma mark - UIAlertView for Add New Minor Delegation
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSLog(#"Adding Minor Goal Canceled!");
}
else
{
// creating string will carry textField value
NSString *minorTitle = [[alertView textFieldAtIndex:0]text];
// creating new minor goal
MinorGoal *newMinorGoal = [NSEntityDescription
insertNewObjectForEntityForName:#"MinorGoal"
inManagedObjectContext:self.selectedGoal.managedObjectContext];
// setting title of new minor goal
newMinorGoal.title = minorTitle;
[self.selectedGoal addMinorGoalObject:newMinorGoal];
// saving
NSError *error = nil;
if (![self.selectedGoal.managedObjectContext save:&error]) {
NSLog(#"Error saving new minor goal: %#", error);
}
NSLog(#"we save %# to %# and theres %lu in it", newMinorGoal.title, self.selectedGoal.title, (unsigned long) [self.selectedGoal.minorGoal count]);
// fetching
[self.fetchedResultsController performFetch:&error];
// reloading tableView data
[self.tableView reloadData];
}
}
#end
Just tell me the right way to fetch the right child object, and should i put them in a NSSet?
It appears that you are using a NSFetchedResultsController to get ALL MinorGoal instances, but you just want to show the child MinorGoals. If you want to use an NSFetchedResultsController then you need to add a predicate to the fetch so that it only returns the MinorGoals that are children of the selected Goal. Assuming that you have created a relationship between MinorGoal and Goal called "parentGoal":
fetchRequest.predicate = [NSPredicate predicateWithFormat:#"self.parentGoal = %#", self.selectedGoal];
Alternatively, don't us the NSFetchedResultsController and instead use the relationship. You will need to convert the NSSet to an array and sort it as the previous answer.
Store your parent object somewhere in your child view controller, typically it should be like
.h file:
#property (nonactomic, strong) ParentObject *parentObject;
.m file
- (id)initWithObject:(ParentObject *)parent {
…
_parentObject = parent;
…
}
then fetching:
(you should have #property (nonatomic, strong) NSFecthedResultsController *fetchedResultController)
- (NSFetchedResultsController*)fetchedResultController {
if (_fetchedResultController) {
return _fetchedResultController;
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:NSStringFromClass([ChildObject class])];
[request setEntity:entity];
NSSortDescriptor *sortDescription = [NSSortDescriptor sortDescriptorWithKey:#"sortOrder" ascending:YES];
[request setSortDescriptors:#[sortDescription]];
request.predicate = [NSPredicate predicateWithFormat:#"(parent == %#)", self.parentObject];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:[NSManagedObjectContext mainThreadContext] sectionNameKeyPath:nil cacheName:nil];
controller.delegate = self;
_fetchedResultController = controller;
return _fetchedResultController;
}
then implement method
- (void)performFetch {
NSError *error = nil;
[self.fetchedResultController performFetch:&error];
if (![self.fetchedResultController performFetch:&error]) {
[self showAlertWithError:error];
}
else {
[self.tableView reloadData];
}
}
thats it basically you will receive all child objects you need sorted and filtered by predicate
seems like I was doing it the hard way, simply create new array that will hold the child objects.
NSMutableArray *minors = self.selectedGoal.minorGoals.allObjects.
and when you obtain change or add, do it two times, once to the array, and another time with the "self.selectedGoal.managedObjectContext".

table cell showing up in wrong section in table view

DataModel.h code file
#import "DataModel.h"
#import <CoreData/CoreData.h>
#import "SettingsEntity.h"
#import "Constants.h"
#implementation DataModel
NSManagedObjectContext *managedObjectContextEntity;
NSManagedObjectContext *managedObjectContextMessage;
NSManagedObjectModel *managedObjectModel;
NSPersistentStoreCoordinator *persistentStoreCoordinator;
NSEntityDescription *theSettingsEntity;
NSEntityDescription *theMessagesEntity;
-(id) init
{
NSURL *modelURL = [[NSBundle mainBundle] URLForResource:#"SOW" withExtension:#"momd"];
managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
NSError *error = nil;
NSURL *storeURL = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] URLByAppendingPathComponent:[Constants SQLLiteDB]];
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:managedObjectModel];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if (persistentStoreCoordinator != nil) {
managedObjectContextEntity = [[NSManagedObjectContext alloc] init];
[managedObjectContextEntity setPersistentStoreCoordinator:persistentStoreCoordinator];
managedObjectContextMessage = [[NSManagedObjectContext alloc] init];
[managedObjectContextMessage setPersistentStoreCoordinator:persistentStoreCoordinator];
}
theSettingsEntity = [NSEntityDescription entityForName:#"SettingsEntity" inManagedObjectContext:managedObjectContextEntity];
theMessagesEntity = [NSEntityDescription entityForName:#"MessageEntity" inManagedObjectContext:managedObjectContextMessage];
return self;
}
-(void) SaveSetting: (SettingsEntity *)setting
{
NSError *error = nil;
if (managedObjectContextEntity != nil) {
if ([managedObjectContextEntity hasChanges] && ![managedObjectContextEntity save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Confirmation" message:#"Settings were saved successfully." delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil];
[alert show];
}
}
}
-(void) SaveMessage: (MessageEntity *)message
{
NSError *error = nil;
if (managedObjectContextMessage != nil) {
if ([managedObjectContextMessage hasChanges] && ![managedObjectContextMessage save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
-(NSArray *) GetSettingsResult
{
NSManagedObjectContext *context = managedObjectContextEntity;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:theSettingsEntity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"enteredDateTime" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
NSArray *results = [context executeFetchRequest:request error:nil];
return results;
}
-(SettingsEntity *) GetSettingsEntity
{
SettingsEntity *settingsEntity = [NSEntityDescription
insertNewObjectForEntityForName:[theSettingsEntity name]
inManagedObjectContext:managedObjectContextEntity];
return settingsEntity;
}
-(NSArray *) GetMessageResult
{
NSFetchRequest *request = [self GetMessageFetchRequest];
NSArray *results = [managedObjectContextMessage executeFetchRequest:request error:nil];
return results;
}
-(NSFetchRequest *) GetMessageFetchRequest
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:theMessagesEntity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"sentDateTime" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
return request;
}
-(NSFetchedResultsController *) GetMessageFetchResultsController
{
NSFetchRequest *fetchRequest = [self GetMessageFetchRequest];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContextMessage sectionNameKeyPath:#"typeMessage" cacheName:nil];
return aFetchedResultsController;
}
-(MessageEntity *) GetMessageEntity
{
MessageEntity *mEntity = [NSEntityDescription
insertNewObjectForEntityForName:[theMessagesEntity name]
inManagedObjectContext:managedObjectContextMessage];
return mEntity;
}
#end
HistoryTableView code file is as follows:
#import "HistoryTableViewController.h"
#import "MessageEntity.h"
#import "DataModel.h"
#import "HistoryDetailViewController.h"
#import "Constants.h"
#interface HistoryTableViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation HistoryTableViewController
//todo: zulfiqar review this line of code.
#synthesize fetchedResultsController = __fetchedResultsController;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
//todo: get fetched controller here.. and reuse it every where in rest of this class.
}
/* faisal code starts here */
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSFetchedResultsController *c = [self fetchedResultsController];
NSArray *titles = [c sectionIndexTitles];
NSString *title = titles[section];
if ([title isEqualToString:#"E"])
{
return [Constants Email];
}
else if([title isEqualToString:#"T"])
{
return [Constants Text];
}
else
{
return [Constants Call];
}
}
- (NSArray *)sectionIndexTitlesForTableView: (UITableView *)aTableView
{
NSFetchedResultsController *c = [self fetchedResultsController];
return [c sectionIndexTitles];
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSFetchedResultsController *c = [self fetchedResultsController];
id<NSFetchedResultsSectionInfo> sectionInfo = c.sections[section];
return sectionInfo.numberOfObjects;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSFetchedResultsController *c = [self fetchedResultsController];
return c.sections.count;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *path = self.tableView.indexPathForSelectedRow;
HistoryDetailViewController *hdvc = segue.destinationViewController;
NSFetchedResultsController *c = [self fetchedResultsController];
MessageEntity *message = (MessageEntity *)[c objectAtIndexPath:path];
hdvc.currentMessageEntity = message;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
/*
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSFetchedResultsController *c = [self fetchedResultsController];
id <NSFetchedResultsSectionInfo> sectionInfo = c.sections[section];
return sectionInfo.numberOfObjects;
}
*/
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSFetchedResultsController *c = [self fetchedResultsController];
NSString *CellIdentifier = [NSString stringWithFormat:#"Cell"];// %d_%d",indexPath.section,indexPath.row];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
MessageEntity *message = (MessageEntity *)[c objectAtIndexPath:indexPath];
cell.textLabel.text = message.typeMessage;
return cell;
/*
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"EEE. MMM. dd, yyyy HH:mm"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSFetchedResultsController *c = [self fetchedResultsController];
MessageEntity *message = (MessageEntity *)[c objectAtIndexPath:indexPath];
NSString *sentDateTime = [dateFormat stringFromDate:message.sentDateTime];
NSString *contactAdd;
NSLog(message.typeMessage);
if ([message.typeMessage isEqualToString:[Constants Email]])
{
contactAdd = message.toEmailAddress;
}
else
{
NSString *unformatted = message.toPhoneNumber;
NSArray *stringComponents = [NSArray arrayWithObjects:[unformatted substringWithRange:NSMakeRange(0, 3)],
[unformatted substringWithRange:NSMakeRange(3, 3)],
[unformatted substringWithRange:NSMakeRange(6, [unformatted length]-6)], nil];
contactAdd = [NSString stringWithFormat:#"(%#) %#-%#", [stringComponents objectAtIndex:0], [stringComponents objectAtIndex:1], [stringComponents objectAtIndex:2]];
}
NSString *header = [[NSString alloc] initWithFormat:#"%#",contactAdd];
NSString *detail = [[NSString alloc] initWithFormat:#"%# on %#", message.sentName, sentDateTime];
cell.detailTextLabel.text = detail;
cell.textLabel.text = header;
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;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSFetchedResultsController *c = [self fetchedResultsController];
NSManagedObject *object = [c objectAtIndexPath:indexPath];
NSManagedObjectContext *context = self.fetchedResultsController.managedObjectContext;
[context deleteObject:object];
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;
}
- (void)tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView reloadData];
}
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
DataModel *data = [[DataModel alloc]init];
NSFetchedResultsController *aFetchedResultsController = [data GetMessageFetchResultsController];
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 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 NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
My history table view looks as follows:
**Q. Why Email and Call are getting into wrong section?**
If you set a sectionNameKeyPath for the fetched results controller, then you must also add a first sort descriptor to the fetch request that uses the same key (or a key that generates the same relative ordering).
So for sectionNameKeyPath:#"typeMessage" you should add one sort descriptor for the key "typeMessage":
NSSortDescriptor *sort1 = [[NSSortDescriptor alloc] initWithKey:#"typeMessage" ascending:YES];
NSSortDescriptor *sort2 = [[NSSortDescriptor alloc] initWithKey:#"sentDateTime" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sort1, sort2, nil];
[request setSortDescriptors:sortDescriptors];

Getting an NSInvalidArguementException error

I think it may have to do with over-releasing? It keeps crashing at if (![managedObjectContext save:&error]) like every third time the method is being called (when I add 3 exercises).
Update: I noticed it happens when I go to and from different routine instances.
2011-04-28 04:02:58.160 Curl[8035:707] Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFDictionary controllerWillChangeContent:]: unrecognized selector sent to instance 0x1ba1b0 with userInfo (null)
2011-04-28 04:02:58.353 Curl[8035:707] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary controllerWillChangeContent:]: unrecognized selector sent to instance 0x1ba1b0'
method
-(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 = selectedExercise;
NSLog(#"addExercise theSelectedRoutine: %#", theSelectedRoutine);
[theSelectedRoutine addRoutineToExercisesObject:exercise];
if (![managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(#"%#", error);
NSLog(#"addExercise theSelectedRoutine: %#", theSelectedRoutine);
[self.routineTableView reloadData];
}
Here is full code:
#implementation RoutineDayTableViewController
#synthesize fetchedResultsController;
#synthesize exerciseChooserView;
#synthesize routineTableView;
#synthesize managedObjectContext;
#synthesize selectedExercise;
#synthesize entityArray;
#synthesize theSelectedRoutine;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)dealloc
{
NSLog(#"dealloc");
[fetchedResultsController release];
[selectedExercise release];
[managedObjectContext release];
[exerciseChooserView release];
[routineTableView release];
[entityArray release];
[theSelectedRoutine release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, imagtaes, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.routineTableView.delegate = self;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(exerciseChooser)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
if (managedObjectContext == nil)
{
managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
[managedObjectContext retain];
}
[self loadData];
}
-(void)loadData
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Exercise" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
NSManagedObject *selectedObject = [entityArray objectAtIndex:indexPath.row];
NSLog(#"After managedObjectContext: %#", managedObjectContext);
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
self.entityArray = mutableFetchResults;
[request setPredicate: [NSPredicate predicateWithFormat: #"routineExercises = %#", selectedObject]];
[mutableFetchResults release];
[request release];
}
- (void)viewDidUnload
{
NSLog(#"viewDidUnload");
[super viewDidUnload];
self.exerciseChooserView = nil;
self.routineTableView = nil;
self.fetchedResultsController = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#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 = selectedExercise;
NSLog(#"addExercise theSelectedRoutine: %#", theSelectedRoutine);
[theSelectedRoutine addRoutineToExercisesObject:exercise];
if (![managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(#"%#", error);
NSLog(#"addExercise theSelectedRoutine: %#", theSelectedRoutine);
//[self.routineTableView reloadData];
}
-(void)toggleEdit
{
[self.routineTableView setEditing: !self.routineTableView.editing animated:YES];
if (self.routineTableView.editing)
[self.navigationItem.rightBarButtonItem setTitle:#"Cancel"];
else
[self.navigationItem.rightBarButtonItem setTitle:#"Edit"];
}
#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 (![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();
}
return fetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
}
#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 is the new updated code:
#implementation RoutineDayTableViewController
#synthesize fetchedResultsController;
#synthesize exerciseChooserView;
#synthesize routineTableView;
#synthesize managedObjectContext;
#synthesize selectedExercise;
#synthesize theSelectedRoutine;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (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];
// Release any cached data, imagtaes, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.routineTableView.delegate = self;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(exerciseChooser)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
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;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#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);
[theSelectedRoutine addRoutineToExercisesObject:exercise];
if (![fetchedResultsController.managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(#"%#", error);
NSLog(#"addExercise theSelectedRoutine: %#", theSelectedRoutine);
//[self.routineTableView reloadData];
[exercise release];
[error release];
}
-(void)toggleEdit
{
[self.routineTableView setEditing: !self.routineTableView.editing animated:YES];
if (self.routineTableView.editing)
[self.navigationItem.rightBarButtonItem setTitle:#"Cancel"];
else
[self.navigationItem.rightBarButtonItem setTitle:#"Edit"];
}
#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
You are mixing two entirely separate means of accessing the Core Data information. You should have only one context reference and one fetch for each tableview. You have at least two fetches operating at the same time and two context references. You need to pick one or the other. If you are using a fetched results controller, then you don't need the code in either viewDidLoad and loadData.
You also need to use the self reference when referring to properties e.g. you need to use self.selectedExercise instead of just selectedExercise. Only the self reference form gives you automatic retention and release.
I see a few issues with your code.
The one most probably causing the error is that the fetchedResultsController method leaks a reference to the NSFetchedResultsController, along with a few other objects. The releases must occur before the return, not after.
Why does loadData add a predicate to the request after using it?
What is even the point of loadData? It sets up entityArray, which doesn't seem to be used anywhere else. Left over from before you added fetchedResultsController?
tableView:commitEditingStyle:forRowAtIndexPath: deletes an object from fetchedResultsController.managedObjectContext, but then saves self.managedObjectContext instead. This should work since those should always be the same, but it would be more semantically correct to use the same object for both operations.

Convert From FetchRequest Array To NSFetchedResultsController

My app currently fetches data on routineViewController's launch and loads it into eventsArray. I was encouraged to try using a NSFetchedResultsController instead.
I'm currently going through the Apple docs to learn more about it but in the meantime if anyone could help me start this conversion process, that would be great.
I added all the fetchresultscontroller code from the apple template but need help combing my addEvent method and the fetchresultcontroller's insertnewobject method. Or do I keep both?
#implementation RoutineTableViewController
#synthesize routineTableView;
#synthesize eventsArray;
#synthesize entered;
#synthesize managedObjectContext;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
if (managedObjectContext == nil)
{
managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Routine" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:#"Edit" style:UIBarButtonItemStyleBordered target:self action:#selector(toggleEdit)];
self.navigationItem.rightBarButtonItem = editButton;
[editButton release];
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.eventsArray = nil;
[super viewDidUnload];
}
-(void)toggleEdit
{
[self.routineTableView setEditing: !self.routineTableView.editing animated:YES];
if (self.routineTableView.editing)
[self.navigationItem.rightBarButtonItem setTitle:#"Done"];
else
[self.navigationItem.rightBarButtonItem setTitle:#"Edit"];
}
- (void)dealloc
{
[managedObjectContext release];
[eventsArray release];
[entered release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark -
#pragma mark Add an event
-(void)addEvent
{
Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:#"Routine" inManagedObjectContext:managedObjectContext];
routine.name=entered;
NSError *error = nil;
if (![managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(#"%#", error);
[eventsArray addObject:routine];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.routineTableView reloadData];
NSInteger lastSection = [self.routineTableView numberOfSections] -1;
[self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.routineTableView numberOfRowsInSection:lastSection]-1 inSection:lastSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
entered = [(AlertPrompt *)alertView enteredText];
if(eventsArray && entered)
{
[self addEvent];
}
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [eventsArray count];
}
- (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];
}
Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
cell.textLabel.text = tempRoutine.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
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;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the managed object at the given index path.
NSManagedObject *eventToDelete = [eventsArray objectAtIndex:indexPath.row];
[managedObjectContext deleteObject:eventToDelete];
// Update the array and table view.
[eventsArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
// Commit the change.
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
}
}
EDIT Added methods for adding events/objects
-(void)addEvent
{
Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:#"Routine" inManagedObjectContext:managedObjectContext];
routine.name=entered;
NSError *error = nil;
if (![managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(#"%#", error);
[eventsArray addObject:routine];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.routineTableView reloadData];
NSInteger lastSection = [self.routineTableView numberOfSections] -1;
[self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.routineTableView numberOfRowsInSection:lastSection]-1 inSection:lastSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
And the fetchResultsController's method:
- (void)insertNewObject
{
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
[newManagedObject setValue:[NSDate date] forKey:#"timeStamp"];
// 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 %#, %#", error, [error userInfo]);
abort();
}
}
Update With Full Code
#implementation RoutineTableViewController
#synthesize routineTableView;
#synthesize eventsArray;
#synthesize entered;
#synthesize managedObjectContext;
#synthesize fetchedResultsController=__fetchedResultsController;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
if (managedObjectContext == nil)
{
managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Routine" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
UIBarButtonItem *editButton = [[UIBarButtonItem alloc]initWithTitle:#"Edit" style:UIBarButtonItemStyleBordered target:self action:#selector(toggleEdit)];
self.navigationItem.rightBarButtonItem = editButton;
[editButton release];
[super viewDidLoad];
}
- (void)viewDidUnload
{
self.eventsArray = nil;
[super viewDidUnload];
}
-(void)toggleEdit
{
[self.routineTableView setEditing: !self.routineTableView.editing animated:YES];
if (self.routineTableView.editing)
[self.navigationItem.rightBarButtonItem setTitle:#"Done"];
else
[self.navigationItem.rightBarButtonItem setTitle:#"Edit"];
}
- (void)dealloc
{
[__fetchedResultsController release];
[managedObjectContext release];
[eventsArray release];
[entered release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark -
#pragma mark Add an event
-(void)addEvent
{
Routine *routine = (Routine *)[NSEntityDescription insertNewObjectForEntityForName:#"Routine" inManagedObjectContext:managedObjectContext];
routine.name=entered;
NSError *error = nil;
if (![managedObjectContext save:&error])
{
// Handle the error.
}
NSLog(#"%#", error);
[eventsArray addObject:routine];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
//[self.routineTableView reloadData];
NSInteger lastSection = [self.routineTableView numberOfSections] -1;
[self.routineTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:[self.routineTableView numberOfRowsInSection:lastSection]-1 inSection:lastSection] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}
/*
- (void)insertNewObject
{
// Create a new instance of the entity managed by the fetched results controller.
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
[newManagedObject setValue:[NSDate date] forKey:#"timeStamp"];
// 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 %#, %#", error, [error userInfo]);
abort();
}
}
*/
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
entered = [(AlertPrompt *)alertView enteredText];
if(eventsArray && entered)
{
[self addEvent];
}
}
}
#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 = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
Routine *tempRoutine = (Routine *)[eventsArray objectAtIndex:indexPath.row];
cell.textLabel.text = tempRoutine.name;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
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;
}
-(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]];
// Update the array and table view.
[eventsArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
// Commit the change.
NSError *error = nil;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[managedObject valueForKey:#"name"] description];
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" 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;
}
/*
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:#"Routine" 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:#"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:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
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();
}
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];
}
/*
// 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];
}
*/
#end
Basically, all you would do would be to move your current fetch into the fetched result controllers setup method. Then you would use the fetched results controller fetchObjects property (which is an array) exactly as you currently use eventsArray.
Look at a Core Data using Navigation based project template in Xcode. It should have a tableview controller configured with a fetched results controller.

Objective-C woes: cellForRowAtIndexPath crashes

I want to the user to be able to search for a record in a DB. The fetch and the results returned work perfectly. I am having a hard time setting the UItableview to display the result tho. The application continually crashes at cellForRowAtIndexPath. Please, someone help before I have a heart attack over here. Thank you.
#implementation SearchViewController
#synthesize mySearchBar;
#synthesize textToSearchFor;
#synthesize myGlobalSearchObject;
#synthesize results;
#synthesize tableView;
#synthesize tempString;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark -
#pragma mark Table View
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//handle selection; push view
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
/* if(nullResulSearch == TRUE){
return 1;
}else {
return[results count];
}
*/
return[results count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1; // Test hack to display multiple rows.
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Search Cell Identifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue2 reuseIdentifier:CellIdentifier] autorelease];
}
NSLog(#"TEMPSTRING %#", tempString);
cell.textLabel.text = tempString;
return cell;
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
}
- (void)viewDidUnload {
self.tableView = nil;
}
- (void)dealloc {
[results release];
[mySearchBar release];
[textToSearchFor release];
[myGlobalSearchObject release];
[super dealloc];
}
#pragma mark -
#pragma mark Search Function & Fetch Controller
- (NSManagedObject *)SearchDatabaseForText:(NSString *)passdTextToSearchFor{
NSManagedObject *searchObj;
UndergroundBaseballAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = appDelegate.managedObjectContext;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name == [c]%#", passdTextToSearchFor];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Entry" inManagedObjectContext:managedObjectContext];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[request setEntity: entity];
[request setPredicate: predicate];
NSError *error;
results = [managedObjectContext executeFetchRequest:request error:&error];
if([results count] == 0){
NSLog(#"No results found");
searchObj = nil;
nullResulSearch == TRUE;
}else{
if ([[[results objectAtIndex:0] name] caseInsensitiveCompare:passdTextToSearchFor] == 0) {
NSLog(#"results %#", [[results objectAtIndex:0] name]);
searchObj = [results objectAtIndex:0];
nullResulSearch == FALSE;
}else{
NSLog(#"No results found");
searchObj = nil;
nullResulSearch == TRUE;
}
}
[tableView reloadData];
[request release];
[sortDescriptors release];
return searchObj;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
textToSearchFor = mySearchBar.text;
NSLog(#"textToSearchFor: %#", textToSearchFor);
myGlobalSearchObject = [self SearchDatabaseForText:textToSearchFor];
NSLog(#"myGlobalSearchObject: %#", myGlobalSearchObject);
tempString = [myGlobalSearchObject valueForKey:#"name"];
NSLog(#"tempString: %#", tempString);
}
#end
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UILongPressGestureRecognizer isEqualToString:]: unrecognized selector sent to instance 0x3d46c20'
The problem may be to do with reference counting.
in - (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar method, try either
self.tempString = [myGlobalSearchObject valueForKey:#"name"];
(assuming tempString is set to retain)
OR
tempString = [[myGlobalSearchObject valueForKey:#"name"] retain];
I would also advise doing some checking for nil values. i.e. what if [myGlobalSearchObject valueForKey:#"name"] == nil?