I used core data to set up all of my entities. But when I try to create a new customer entity and send it to the modal addCustomer view controller I keep getting this error.
* Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[UINavigationController
setCustomer:]: unrecognized selector sent to instance 0x8854700'
The error occurs in AccountListTableViewController.m when the program gets to addController.customer = newCustomer in the prepareForSegue.
Here is the code:
AccountListTableViewController.h
#import <UIKit/UIKit.h>
#import "CustomerAddViewController.h"
#class Customer;
#interface AccountListTableViewController : UITableViewController <CustomerAddDelegate, NSFetchedResultsControllerDelegate> {
#private
NSFetchedResultsController *fetchedResultsController;
NSManagedObjectContext *managedObjectContext;
}
#property (nonatomic, retain) NSFetchedResultsController *fetchedResultsController;
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#end
AccountListTableViewController.m
#import "AccountListTableViewController.h"
#import "AccountListCell.h"
#import "Customer.h"
#import "AppDelegate.h"
#implementation AccountListTableViewController
#synthesize managedObjectContext, fetchedResultsController;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString:#"AddAccountSegue"] ) {
CustomerAddViewController *addController = [segue destinationViewController];
addController.delegate = self;
Customer *newCustomer = [NSEntityDescription insertNewObjectForEntityForName:#"Customer" inManagedObjectContext:self.managedObjectContext];
addController.customer = newCustomer;
}
}
-(void)customerAddViewController:(CustomerAddViewController *)customerAddViewController didAddCustomer:(Customer *)customer{
[self dismissModalViewControllerAnimated:YES];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
//I added this to keep from crashing
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", managedObjectContext);
}
[super viewDidLoad];
// 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;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//#warning Potentially incomplete method implementation.
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//Customer *customer = [self.fetchedResultsController objectAtIndexPath:indexPath];
AccountListCell *cell = [tableView dequeueReusableCellWithIdentifier:#"AccountCellReuseIdentifier"];
Customer *aCustomer = (Customer *)[fetchedResultsController objectAtIndexPath:indexPath];
cell.customer = aCustomer;
// static NSString *CellIdentifier = #"Cell";
//
// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// if (cell == nil) {
// cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// }
// Configure the cell...
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 row from the data source
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// 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];
*/
}
- (NSFetchedResultsController *)fetchedResultsController {
// Set up the fetched results controller if needed.
if (fetchedResultsController == nil) {
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Customer" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"lastName" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
// [aFetchedResultsController release];
// [fetchRequest release];
// [sortDescriptor release];
// [sortDescriptors release];
}
return fetchedResultsController;
}
/**
Delegate methods of NSFetchedResultsController to respond to additions, removals and so on.
*/
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller is about to start sending change notifications, so prepare the table view for updates.
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
// case NSFetchedResultsChangeUpdate:
// [self configureCell:(AccountListCell *)[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
// break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// The fetch controller has sent all current change notifications, so tell the table view to process all updates.
[self.tableView endUpdates];
}
#end
CustomerAddViewController.h
#import <UIKit/UIKit.h>
#import "Customer.h"
#class Customer;
#protocol CustomerAddDelegate;
#interface CustomerAddViewController : UITableViewController{
Customer *customer;
UITextField *firstName;
UITextField *lastName;
UITextField *address;
UITextField *city;
UITextField *state;
UITextField *zip;
UITextField *homePhone;
UITextField *cellPhone;
UITextField *email;
id <CustomerAddDelegate> delegate;
}
#property (nonatomic, strong) Customer *customer;
#property (nonatomic, strong) IBOutlet UITextField *firstName;
#property (nonatomic, strong) IBOutlet UITextField *lastName;
#property (nonatomic, strong) IBOutlet UITextField *address;
#property (nonatomic, strong) IBOutlet UITextField *city;
#property (nonatomic, strong) IBOutlet UITextField *state;
#property (nonatomic, strong) IBOutlet UITextField *zip;
#property (nonatomic, strong) IBOutlet UITextField *homePhone;
#property (nonatomic, strong) IBOutlet UITextField *cellPhone;
#property (nonatomic, strong) IBOutlet UITextField *email;
#property (nonatomic, strong) id <CustomerAddDelegate> delegate;
- (IBAction) saveCustomer;
- (IBAction) cancel;
#end
#protocol CustomerAddDelegate <NSObject>
-(void)customerAddViewController:(CustomerAddViewController *)customerAddViewController didAddCustomer:(Customer *)customer;
#end
CustomerAddView.m
#define NAME 0
#define ADDRESS 1
#define CONTACT 2
#import "CustomerAddViewController.h"
#import "Customer.h"
#implementation CustomerAddViewController
#synthesize firstName, lastName, address, city, state, zip, homePhone, cellPhone, email, customer, delegate;
//- (id)initWithStyle:(UITableViewStyle)style
//{
// self = [super initWithStyle:style];
// if (self) {
// // Custom initialization
// }
// return self;
//}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
// [super viewDidLoad];
// 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;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
//This stuff not needed because we are setting static sections and rows in storyboard
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
// return 3;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
//{
// NSInteger rows = 0;
// switch (section) {
// case NAME:
// rows = 2;
// break;
// case ADDRESS:
// rows = 4;
// break;
// case CONTACT:
// rows = 3;
// break;
// }
//
// 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:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// }
//
// // Configure the cell...
//
// 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 row from the data source
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// 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];
*/
}
#end
CustomerAddViewController *addController = [segue destinationViewController];
Are you sure your destination view controller is a CustomerAddViewController?
It looks like it's actually a navigation controller. Hence the [UINavigationController setCustomer:]: unrecognized selector sent to instance 0x8854700 when you do addController.customer = newCustomer
In continuation to the first answer, the correct way to then reach the destination view controller when a navigation controller is between is as follows
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"AddAccountSegue"])
{
UINavigationController *navigationController = segue.destinationViewController;
CustomerAddViewController *addController = (id)[[navigationController viewControllers] objectAtIndex:0];
[addController setCustomer:yourObject];
}
}
Related
I have a problem that Im sure many objectiveC developers would be able to solve pretty easily. Im developing an app which is a dynamic tableview with different groups that the user can create. The user can enter a number of groups with different totals. I am trying to sum the total of all the groups created.
The IBAction I am using to calculate the subtotal is
- (IBAction)Calculate:(id)sender {
//---------------
NSInteger Tempsum = [[_dataArray valueForKeyPath:#"#sum.name2"] integerValue];
_TotalAnimals.text = [[NSString alloc] initWithFormat:#"%.1ld", (long)Tempsum];
//--------------
}
I have created the following code in the .m file of my tableview and also created a NSArray property called;
#property NSArray *dataArray;
however I am unsure as to the correct code to use to be able to link the result ( #"#sum.name2" ) to the text value in the Tableviewcontroller ( _TotalAnimals.text)
Any help with this problem would be much appreciated. below is the full code for the .m file
#import "TSPViewController.h"
#import <CoreData/CoreData.h>
#import "TSPToDoCell.h"
#import "TSPAddToDoViewController.h"
#import "TSPUpdateToDoViewController.h"
int TempTotalAnimals = 0;
int TotalAnimals = 0;
int Tempsum = 0;
#interface TSPViewController () <NSFetchedResultsControllerDelegate>
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) NSIndexPath *selection;
#property NSArray *dataArray;
#end
#implementation TSPViewController
#pragma mark -
#pragma mark View Life Cycle
- (void)viewDidLoad {
[super viewDidLoad];
// Initialize Fetch Request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"TSPItem"];
// Add Sort Descriptors
[fetchRequest setSortDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"createdAt" ascending:YES]]];
// Initialize Fetched Results Controller
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
// Configure Fetched Results Controller
[self.fetchedResultsController setDelegate:self];
// Perform Fetch
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];
if (error) {
NSLog(#"Unable to perform fetch.");
NSLog(#"%#, %#", error, error.localizedDescription);
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"addToDoViewController"]) {
// Obtain Reference to View Controller
UINavigationController *nc = (UINavigationController *)[segue destinationViewController];
TSPAddToDoViewController *vc = (TSPAddToDoViewController *)[nc topViewController];
// Configure View Controller
[vc setManagedObjectContext:self.managedObjectContext];
} else if ([segue.identifier isEqualToString:#"updateToDoViewController"]) {
// Obtain Reference to View Controller
TSPUpdateToDoViewController *vc = (TSPUpdateToDoViewController *)[segue destinationViewController];
// Configure View Controller
[vc setManagedObjectContext:self.managedObjectContext];
if (self.selection) {
// Fetch Record
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:self.selection];
if (record) {
[vc setRecord:record];
}
// Reset Selection
[self setSelection:nil];
}
}
}
#pragma mark -
#pragma mark Fetched Results Controller Delegate Methods
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
switch (type) {
case NSFetchedResultsChangeInsert: {
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeDelete: {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
case NSFetchedResultsChangeUpdate: {
[self configureCell:(TSPToDoCell *)[self.tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
}
case NSFetchedResultsChangeMove: {
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (void)configureCell:(TSPToDoCell *)cell atIndexPath:(NSIndexPath *)indexPath {
// Fetch Record
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
// Update Cell
[cell.nameLabel setText:[record valueForKey:#"name"]];
[cell.nameLabel2 setText:[record valueForKey:#"name2"]];
[cell.doneButton setSelected:[[record valueForKey:#"done"] boolValue]];
[cell setDidTapButtonBlock:^{
BOOL isDone = [[record valueForKey:#"done"] boolValue];
// Update Record
[record setValue:#(!isDone) forKey:#"done"];
}];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObject *record = [self.fetchedResultsController objectAtIndexPath:indexPath];
if (record) {
[self.fetchedResultsController.managedObjectContext deleteObject:record];
}
}
}
#pragma mark -
#pragma mark Table View Delegate Methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Store Selection
[self setSelection:indexPath];
// Perform Segue
[self performSegueWithIdentifier:#"updateToDoViewController" sender:self];
}
// NSArray Below============
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *sections = [self.fetchedResultsController sections];
id<NSFetchedResultsSectionInfo> sectionInfo = [sections objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TSPToDoCell *cell = (TSPToDoCell *)[tableView dequeueReusableCellWithIdentifier:#"ToDoCell" forIndexPath:indexPath];
// Configure Table View Cell
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (IBAction)Calculate:(id)sender {
//---------------
NSInteger Tempsum = [[_dataArray valueForKeyPath:#"#sum.name2"] integerValue];
_TotalAnimals.text = [[NSString alloc] initWithFormat:#"%.1ld", (long)Tempsum];
//--------------
}
/*
//---------------
NSInteger TempsumTotalAnimals = [[_charactersArray valueForKeyPath:#"#sum.passenger"] integerValue];
_TotalAnimals.text = [[NSString alloc] initWithFormat:#"%.1ld", (long)TempsumTotalAnimals];
//--------------
*/
#end
I have several CoreDataTableViewControllers that utilize the helper class from Paul Hegarty's course. Everyone of them works except this one, and I cannot see a difference.
When the table first comes up, it is correctly populated and the segue executes properly when a cell is selected. However when I hit the back button, the table displays (null), (null) everywhere.
I have tried every variant of calling [self useDocument] that I can think of, still to no avail. Any thoughts? Thanks in advance.
//
// TeamTableViewController.m
//
#import "TeamTableViewController.h"
#import "iTrackAppDelegate.h"
#import "CoreDataTableViewController.h"
#import "SchoolRecords.h"
#import "ScheduleViewController.h"
#interface TeamTableViewController ()
#property NSInteger toggle;
#end
#implementation TeamTableViewController
#synthesize iTrackContext = _iTrackContext;
#synthesize schoolSelected = _schoolSelected;
-(void) setSchoolSelected:(SchoolRecords *)schoolSelected
{
_schoolSelected = schoolSelected;
}
-(void) setITrackContext:(NSManagedObjectContext *)iTrackContext
{
if(_iTrackContext != iTrackContext){
if (!iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
_iTrackContext = cdh.context;
} else {
_iTrackContext = iTrackContext;
}
}
[self useDocument];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)setupFetchedResultsController // attaches an NSFetchRequest to this UITableViewController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"SchoolRecords"];
// no predicate because we want ALL the Athletes
request.sortDescriptors = [NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:#"schoolName" ascending:YES],
nil];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.iTrackContext
sectionNameKeyPath:nil
cacheName:nil];
__block NSInteger myCount;
int64_t delayInSeconds = 5.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
[self.iTrackContext performBlock:^(void){NSError* requestError = nil;
myCount = [self.iTrackContext countForFetchRequest:request error:&requestError];
NSLog(#"In %# and count of iTrackContext = %lu", NSStringFromClass([self class]),(unsigned long)myCount);
}];
if (!myCount || myCount == 0) {
[self displayAlertBoxWithTitle:#"No Teams" message:#"Have you added athletes yet? \nPlease go to Add Athletes" cancelButton:#"Okay"];
}
});
}
- (void)useDocument
{
if (self.iTrackContext) {
[self setupFetchedResultsController];
} else {
NSString* errorText = #"A problem arose opening the search results database of Athletes.";
[self displayAlertBoxWithTitle:#"File Error" message:errorText cancelButton:#"Okay"];
}
}
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
if (!self.iTrackContext) {
MyCoreDataHandler* cdh =
[(iTrackAppDelegate *) [[UIApplication sharedApplication] delegate] cdh];
[self setITrackContext:cdh.context];
} else {
NSLog(#"In %# of %#. Getting ready to call useDocument",NSStringFromSelector(_cmd), self.class);
[self useDocument];
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// If divide into sections use line below otherwise return 1.
// return [[self.fetchedResultsController sections] count];
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Do not really need this with only one section, but makes code usable if add sections later.
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"teamInformation";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
SchoolRecords *schoolResults = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString* titleText = schoolResults.schoolName;
cell.textLabel.text = titleText;
cell.detailTextLabel.text = [NSMutableString stringWithFormat:#"%#, %#", schoolResults.schoolCity, schoolResults.schoolState];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
# pragma navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
[self setSchoolSelected:[self.fetchedResultsController objectAtIndexPath:indexPath]];
// be somewhat generic here (slightly advanced usage)
// we'll segue to ANY view controller that has a photographer #property
if ([segue.identifier isEqualToString:#"scheduleDetailSegue"]) {
// use performSelector:withObject: to send without compiler checking
// (which is acceptable here because we used introspection to be sure this is okay)
NSLog(#"Preparing to passing school with schoolID = %#", self.schoolSelected.schoolID);
[segue.destinationViewController convenienceMethodForSettingSchool:self.schoolSelected];
}
}
- (void) displayAlertBoxWithTitle:(NSString*)title message:(NSString*) myMessage cancelButton:(NSString*) cancelText
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
message:myMessage
delegate:nil
cancelButtonTitle:cancelText
otherButtonTitles:nil];
[alert show];
}
#end
Well, I am not certain what the problem was. I ended up deleting the "offending" TableViewControllers in StoryBoard and recreated them. That did the trick. In retrospect, I wonder if I did not specify the wrong type of segue from my tabViewController. But I deleted it before I thought of that possibility.
I have a UITableView populated by data parsed from xml. The parsing works but the table remains blank.
The console shows that the xml form the url is parsed and shows its components. It also shows the number of objects that the rows of tableview should have when asked in a different function but the numberOfRowsInSection: is returning Null. Therefore, the tableView in the Simulator remains blank.
Here is my code. It is simple code from a tutorial:
+++++++++++++++++ RootViewController.h++++++++++++++++++++++
#import < UIKit/UIKit.h >
#interface RootViewController : UITableViewController < NSXMLParserDelegate >{
IBOutlet UITableView *newsTable;
UIActivityIndicatorView *activityIndicator;
CGSize cellSize;
NSXMLParser *rssParser;
NSMutableArray *stories;
NSMutableDictionary *item;
NSString *currentElement;
NSMutableString *currentTitle, *currentDate, *currentSummary, *currentLink;
}
#property (nonatomic, retain) NSMutableArray *stories;
#property (nonatomic, retain) IBOutlet UITableView *newsTable;
-(void)parseXMLFileAtURL:(NSString *)URL;
#end
+++++++++++++++++++++++++++ RootViewController.m ++++++++++++++++++++++++++++++++++++++
#import "RootViewController.h"
#implementation RootViewController
#synthesize newsTable, stories;
-(void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[newsTable reloadData];
}
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if([stories count] == 0){
NSString *path = #"http://feeds.feedburner.com/TheAppleBlog";
[self parseXMLFileAtURL:path];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}
// Customize the number of sections in the table view.
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(void)parseXMLFileAtURL:(NSString *)URL {
stories = [[NSMutableArray alloc] init];
NSURL *xmlURL = [NSURL URLWithString:URL];
rssParser = [[NSXMLParser alloc] initWithContentsOfURL:xmlURL];
[rssParser setDelegate:self];
[rssParser setShouldProcessNamespaces:NO];
[rssParser setShouldReportNamespacePrefixes:NO];
[rssParser setShouldResolveExternalEntities:NO];
[rssParser parse];
}
-(void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(#"Found file and started parsing");
}
-(void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError{
NSString *errorString = [NSString stringWithFormat:#"Unable to download story feed from the website (error code %i)", [parseError code]];
NSLog(#"error parsing XML: %#", errorString);
UIAlertView *errorAlert = [[UIAlertView alloc]:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitle:nil];
[errorAlert show];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict{
NSLog(#"Found this Element %#", elementName);
currentElement = [elementName copy];
if ([elementName isEqualToString:#"item"]) {
item = [[NSMutableDictionary alloc] init];
currentTitle = [[NSMutableString alloc] init];
currentDate = [[NSMutableString alloc] init];
currentSummary = [[NSMutableString alloc] init];
currentLink = [[NSMutableString alloc] init];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
NSLog(#"End this Element %#", elementName);
if ([elementName isEqualToString:#"item"]) {
[item setObject:currentTitle forKey:#"title"];
[item setObject:currentLink forKey:#"link"];
[item setObject:currentSummary forKey:#"summary"];
[item setObject:currentDate forKey:#"date"];
[stories addObject:[item copy]];
NSLog(#"adding Story : %#",currentTitle);
}
}
// Customize the number of rows in the table view.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"Count is = %#", [stories count]);
return [stories count];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{
NSLog(#"Found characters: %#", string);
if([currentElement isEqualToString:#"title"]){
[currentTitle appendString:string];
NSLog(#"The Title is : %#", currentTitle);
}
else if([currentElement isEqualToString:#"link"]){
[currentLink appendString:string];
NSLog(#"The Link is : %#", currentLink);
}
else if([currentElement isEqualToString:#"description"]){
[currentSummary appendString:string];
NSLog(#"The summary is : %#", currentSummary);
}
else if([currentElement isEqualToString:#"pubDate"]){
[currentDate appendString:string];
NSLog(#"The Date is : %#", currentDate);
}
}
-(void)parserDidEndDocument:(NSXMLParser *)parser{
[activityIndicator stopAnimating];
[activityIndicator removeFromSuperview];
NSLog(#"Stories array has %d items", [stories count]);
NSLog(#"Stories are : %#",stories);
}
// Customize the appearance of table view cells.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = #"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
}
// Configure the cell.
cell.textLabel.text = (NSString *)[[stories objectAtIndex:indexPath.row] objectForKey:#"title"];
return cell;
}
-(void)dealloc {
[super dealloc];
[newsTable release];
[currentDate release];
[currentElement release];
[currentSummary release];
[currentLink release];
[stories release];
[item release];
[currentTitle release];
[rssParser release];
}
You have to tell the table view that there is new data by calling reloadData after you have parsed the XML.
Is the newsTable outlet properly connected to the table view in IB? And, is the table's dataSource outlet set to your view controller?
To expand on #omz's correct answer:
The method numberOfRowsInSection is not returning NULL but zero. (In Objective-C, nil==zero and Null is a singleton object.)
The only reason that it would return zero is if the [stories count] returns zero and the only reason [stories count] would return zero is if it has no elements. Since you've confirmed that the parse works and stories has elements, then the tableview must be seeking data before the parse occurs.
This method is called first and it is the only place you reload data:
-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[newsTable reloadData];
// You trigger the tableview to call numberOfRowsInSection before stories is populated.
}
This method is called only after the tableview has appeared on screen and it is only after the tableview appears that you populate stories.
-(void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
if([stories count] == 0){
NSString *path = #"http://feeds.feedburner.com/TheAppleBlog";
[self parseXMLFileAtURL:path];
}
cellSize = CGSizeMake([newsTable bounds].size.width, 60);
}
However, nothing triggers the tableview to call numberOfRowsInSection again so the tableview remains blank. Simply moving the populating of stories to viewWillAppear: will fix the problem.
Each time you alter the data upon which the tableview depends (regardless of reason) you must call reloadData otherwise the tableview remains unaware that it no longer displays the current data set.
As an aside, you should use the dot notation when referring to properties to ensure they are properly retained. You should use self.stories to refer to the stories property. Otherwise, it might be released at random causing an equally random crash.
I have created one application with core data but is unable to display the data in table view. I am writing the code below which I have written for fetching the results:
#import "RootViewController.h"
#import "DetailViewController.h"
#import "AddViewController.h"
#import "EmployeeDetailsAppDelegate.h"
/*
This template does not ensure user interface consistency during editing operations in the table view. You must implement appropriate methods to provide the user experience you require.
*/
#interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation RootViewController
#synthesize detailViewController, fetchedResultsController, managedObjectContext;
#synthesize array;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
// EmployeeDetailsAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
self.title = #"Employee Name";
self.navigationItem.rightBarButtonItem = self.editButtonItem;
NSMutableArray *tempArr = [[NSMutableArray alloc]initWithCapacity:0];
if (self.fetchedResultsController) {
tempArr = self.fetchedResultsController.fetchedObjects;
}
self.array = tempArr;
[super viewDidLoad];
[tempArr release];
}
- (void)viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
[super viewWillAppear:animated];
}
/*
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
*/
/*
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
*/
/*
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
*/
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Ensure that the view controller supports rotation and that the split view can therefore show in both portrait and landscape.
return YES;
}
#pragma mark -
#pragma mark Add a new object
- (void)insertNewObject:(id)sender {
AddViewController *add = [[AddViewController alloc]initWithNibName:#"AddViewController" bundle:nil];
self.modalPresentationStyle = UIModalPresentationFormSheet;
add.wantsFullScreenLayout = NO;
[self presentModalViewController:add animated:YES];
[add release];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if([self.array count])
{
return [array count];
}
return 1;
}
- (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] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
-(void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath{
AddViewController *detail = [fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = detail.empName.text;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the managed object.
NSManagedObject *objectToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
if (self.detailViewController.detailItem == objectToDelete) {
self.detailViewController.detailItem = nil;
}
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
[context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error;
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();
}
}
}
- (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 *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Set the detail item in the detail view controller.
detailViewController = [[DetailViewController alloc]initWithStyle:UITableViewStylePlain];
AddViewController *selectedName = (AddViewController *)[[self fetchedResultsController]objectAtIndexPath:indexPath];
detailViewController.detail = selectedName;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
#pragma mark -
#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:#"Details" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:#"EmployeeName" ascending:NO];
NSSortDescriptor *idDescriptor = [[NSSortDescriptor alloc] initWithKey:#"EmployeeID" ascending:NO];
NSMutableArray *sortDescriptors = [[NSMutableArray alloc] initWithObjects:nameDescriptor, idDescriptor, nil];
self.array = sortDescriptors;
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[nameDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
}
#pragma mark -
#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];
}
#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 {
self.fetchedResultsController = nil;
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
self.array = nil;
}
- (void)dealloc {
[array release];
[detailViewController release];
[fetchedResultsController release];
[managedObjectContext release];
[super dealloc];
}
#end
The problem is I am getting a warning with the following line:
tempArr = self.fetchedResultsController.fetchedObjects;
The warning is: "/Users/satyam/Desktop/EmployeeDetails/Classes/RootViewController.m:43:0 /Users/satyam/Desktop/EmployeeDetails/Classes/RootViewController.m:43: warning: incompatible Objective-C types assigning 'struct NSArray *', expected 'struct NSMutableArray *'"
Just read the warning word for word.
you try to assign an NSArray to a variable that expects a NSMutableArray.
self.fetchedResultsController.fetchedObjects is an NSArray
tempArr is an NSMutableArray
but if you use the NSFetchedResultsController you don't need your own data array at all.
The NSFetchedResultsController handles all the data for you.
so maybe you want to replace
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if([self.array count])
{
return [array count];
}
return 1;
}
with
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
your own datasource is invalid anyway. because you assign the sortDescriptor used for the NSFetchedResultsController to it.
NSMutableArray *sortDescriptors = [[NSMutableArray alloc] initWithObjects:nameDescriptor, idDescriptor, nil];
self.array = sortDescriptors;
I don't know what you wanted to achieve by doing this.
I want to add simple search bar in the table view. Program getting run with no error, but when I try to add text in search bar, program gets terminates
following is my code:
#interface RootViewController : UITableViewController<UISearchBarDelegate> {
NSArray *list;
IBOutlet UISearchBar *searchBar;
NSMutableArray *searchresult;
BOOL isSearchon;
BOOL canSelectRow;
}
#property(nonatomic, retain)NSArray *list;
#property(nonatomic, retain)IBOutlet UISearchBar *searchBar;
-(void)doneSearching:(id)sender;
-(void)searchlist;
#end
//in .m
#implementation RootViewController
#synthesize list,searchBar;
-(void)doneSearching:(id)sender
{
isSearchon=NO;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
self.navigationItem.rightBarButtonItem=nil;
[searchBar resignFirstResponder];
[self.tableView reloadData];
}
-(void)searchlist
{NSString *searchText = searchBar.text;
[searchresult removeAllObjects];
for(NSString *str in list)
{
NSRange titleResultsRange=[str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[searchresult addObject:str];
}
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
[self searchlist];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
if([searchText length]>0)
{isSearchon =YES;
canSelectRow=YES;
self.tableView.scrollEnabled=YES;
[self searchlist];}
else{
isSearchon =NO;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
}
[self.tableView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
list = [[NSArray alloc]initWithObjects:#"rohan",#"vidhya",#"kavita",#"pushkar",nil];
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType=UITextAutocorrectionTypeYes;
searchresult=[[NSMutableArray alloc]init];
isSearchon =NO;
canSelectRow=YES;
self.navigationItem.title = #"Names";
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
isSearchon =YES;
canSelectRow=NO;
self.tableView.scrollEnabled=NO;
self.navigationItem.rightBarButtonItem=[[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:#selector(doneSearching:)]autorelease];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(isSearchon){
return [searchresult count];}
else{
return [list 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] autorelease];
}
if(isSearchon)
{
cell.text=[searchresult objectAtIndex:indexPath.row];}
else{
cell.text=[list objectAtIndex:indexPath.row];}
// Configure the cell.
return cell;
}
- (void)dealloc {
[super dealloc];
[searchBar release];
}
#end
I have edited my code in my question...it works fine nw....AnyOne willing to use searchbar in tableview in Iphones can refer the code.