I want to implement a UISearchDisplayController in a UIViewController, hence there is no UITableView implemented. I created the UISearchBar and UISearchDisplayController and implemented the corresponding delegate methods.
When I run the app and try searching, the table view that should be shown with the search results do not appear. To explain more my app UI, the UIViewController has a map and the search bar is placed in the navigation controller.
What I understood for now, it seems like I should implement a table view in order to be reused for the search results. However, there is no place/need to place a table view. What can I do to fix this? Any hints?
Here is the code how I implemented everything:
- (void)viewDidLoad{
[super viewDidLoad];
// Do any additional setup after loading the view.
_search = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[_search setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
[_search setPlaceholder:#"Search"];
self.navigationItem.titleView = _search;
_searchArray = [[NSMutableArray alloc] initWithObjects:#"Hi", nil];
_searchDisplay = [[UISearchDisplayController alloc] initWithSearchBar:_search contentsController:self];
_searchDisplay.delegate = self;
_searchDisplay.searchResultsDataSource = self;
_searchDisplay.searchResultsDelegate = self;
[_searchDisplay setActive:YES animated:YES];
filteredResults = [[NSMutableArray alloc] init];}
-(void) filterForSearchText:(NSString *) text scope:(NSString *) scope
{
[filteredResults removeAllObjects]; // clearing filter array
NSPredicate *filterPredicate = [NSPredicate predicateWithFormat:#"SELF contains[c] %#",text]; // Creating filter condition
filteredResults = [NSMutableArray arrayWithArray:[_searchArray filteredArrayUsingPredicate:filterPredicate]]; // filtering result
NSLog(#"search %#", filteredResults);
}
#pragma mark - UISearchDisplayDelegate Methods
-(BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterForSearchText:searchString scope:[[[[self searchDisplayController] searchBar] scopeButtonTitles] objectAtIndex:[[[self searchDisplayController] searchBar] selectedScopeButtonIndex] ]];
return YES;
}
-(BOOL) searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterForSearchText:self.searchDisplayController.searchBar.text scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
#import <UIKit/UIKit.h>
#import "RoleDetailTVC.h" // so this class can be an RoleDetailTVCDelegate
#import "CoreDataTableViewController.h" // so we can fetch
#import "Role.h"
#interface RolesTVC : CoreDataTableViewController <RoleDetailTVCDelegate>
#property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
#property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;
#property (strong, nonatomic) Role *selectedRole;
#property (nonatomic, retain) NSMutableArray *searchResults;
#end
#import "RolesTVC.h"
#import "Role.h"
#import "ModelCell.h"
#import <QuartzCore/QuartzCore.h>
#interface RolesTVC ()
{
NSMutableArray *objects;
}
#end
#implementation RolesTVC
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize selectedRole;
#synthesize searchResults;
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
objects = [[NSMutableArray alloc]init];
if(self){
for (int i=1; i<100; i++) {
NSString *str = [NSString stringWithFormat:#"This is the fabulous Row %d",i];
[objects addObject:str];
}
}
return self;
}
//This function is where all the magic happens
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
//1. Setup the CATransform3D structure
CATransform3D rotation;
rotation = CATransform3DMakeRotation( (90.0*M_PI)/180, 0.0, 0.7, 0.4);
rotation.m34 = 1.0/ -600;
//2. Define the initial state (Before the animation)
cell.layer.shadowColor = [[UIColor blackColor]CGColor];
cell.layer.shadowOffset = CGSizeMake(10, 10);
cell.alpha = 0;
cell.layer.transform = rotation;
cell.layer.anchorPoint = CGPointMake(0, 0.5);
//!!!FIX for issue #1 Cell position wrong------------
if(cell.layer.position.x != 0){
cell.layer.position = CGPointMake(0, cell.layer.position.y);
}
//4. Define the final state (After the animation) and commit the animation
[UIView beginAnimations:#"rotation" context:NULL];
[UIView setAnimationDuration:0.8];
cell.layer.transform = CATransform3DIdentity;
cell.alpha = 1;
cell.layer.shadowOffset = CGSizeMake(0, 0);
[UIView commitAnimations];
}
//Helper function to get a random float
- (float)randomFloatBetween:(float)smallNumber and:(float)bigNumber {
float diff = bigNumber - smallNumber;
return (((float) (arc4random() % ((unsigned)RAND_MAX + 1)) / RAND_MAX) * diff) + smallNumber;
}
- (UIColor*)colorFromIndex:(int)index{
UIColor *color;
//Purple
if(index % 3 == 0){
color = [UIColor colorWithRed:0.93 green:0.01 blue:0.55 alpha:1.0];
//Blue
}else if(index % 3 == 1){
color = [UIColor colorWithRed:0.00 green:0.68 blue:0.94 alpha:1.0];
//Blk
}else if(index % 3 == 2){
color = [UIColor blackColor];
}
else if(index % 3 == 3){
color = [UIColor colorWithRed:0.00 green:1.0 blue:0.00 alpha:1.0];
}
return color;
}
#pragma mark -
#pragma mark Fetched Results Controller section
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = #"Role"; // Put your entity name here
//NSLog(#"Setting up a Fetched Results Controller for the Entity named %#", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
[request setFetchLimit:100];
// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:#"Role.name = Blah"];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"name"
ascending:YES
selector:#selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setupFetchedResultsController];
}
/**
* iCloud
*
* #param note Check PersonTVC
*/
- (void)reloadFetchedResults:(NSNotification*)note {
//NSLog(#"Underlying data changed ... refreshing!");
[self performFetch];
}
- (void)viewDidLoad
{
[ADVThemeManager customizeTableView:self.tableView];
[self.tableView reloadData];
/*
* Refresh this view whenever data changes iCloud
*/
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(reloadFetchedResults:)
name:#"RolesTVCSomethingChanged"
object:[[UIApplication sharedApplication] delegate]];
}
- (void)viewDidUnload
{
/**
* iCloud
*
*/
[[NSNotificationCenter defaultCenter] removeObserver:self];
/**
* Search Function
*/
self.searchResults = nil;
}
#pragma mark -
#pragma mark - Table view delegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"RolesCell";
ModelCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"ModelCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// Configure the cell...
Role *role = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.nameLbl.text = role.name;
cell.zoneLbl.text = role.zones;
cell.checkoutLbl.text = role.checkout;
//Set the accessory type.
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
//Configure the cell font
cell.zoneLbl.font = [UIFont fontWithName:#"eurostile-oblique" size:18.0];
cell.nameLbl.font = [UIFont fontWithName:#"eurostile-oblique" size:18.0];
cell.checkoutLbl.font = [UIFont fontWithName:#"eurostile-oblique" size:18.0];
return cell;
}
#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView)
{
return [self.searchResults count];
}
else
{
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 75.f;
}
#pragma mark -
#pragma mark Table view Methods
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.tableView beginUpdates]; // Avoid NSInternalInconsistencyException
// Delete the role object that was swiped
Role *roleToDelete = [self.fetchedResultsController objectAtIndexPath:indexPath];
//NSLog(#"Deleting (%#)", roleToDelete.name);
[self.managedObjectContext deleteObject:roleToDelete];
[self.managedObjectContext save:nil];
// Delete the (now empty) row on the table
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self performFetch];
[self.tableView endUpdates];
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Error! %#",error);
abort();
}
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"Add Role Segue"])
{
// NSLog(#"Setting RolesTVC as a delegate of RoleDetailTVC");
RoleDetailTVC *roleDetailTVC = segue.destinationViewController;
roleDetailTVC.delegate = self;
// NSLog(#"Creating a new role and passing it to RoleDetailTVC");
Role *newRole = [NSEntityDescription insertNewObjectForEntityForName:#"Role"
inManagedObjectContext:self.managedObjectContext];
roleDetailTVC.role = newRole;
// Hide bottom tab bar in the detail view
roleDetailTVC.hidesBottomBarWhenPushed = YES;
}
else if ([segue.identifier isEqualToString:#"Role Detail Segue"])
{
// NSLog(#"Setting RolesTVC as a delegate of RoleDetailTVC");
RoleDetailTVC *roleDetailTVC = segue.destinationViewController;
roleDetailTVC.delegate = self;
// Store selected Role in selectedRole property
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
self.selectedRole = [self.fetchedResultsController objectAtIndexPath:indexPath];
// NSLog(#"Passing selected role (%#) to RoleDetailTVC", self.selectedRole.name);
roleDetailTVC.role = self.selectedRole;
// Hide bottom tab bar in the detail view
roleDetailTVC.hidesBottomBarWhenPushed = YES;
}
else {
// NSLog(#"Unidentified Segue Attempted!");
}
}
- (void)theSaveButtonOnTheRoleDetailTVCWasTapped:(RoleDetailTVC *)controller
{
// do something here like refreshing the table or whatever
// close the delegated view
[controller.navigationController popViewControllerAnimated:YES];
}
// Override to support conditional rearranging of the table view.
-(BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath: (NSIndexPath *) indexPath {
return YES;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath: (NSIndexPath *) indexPath {
return YES;
}
- (void)didReceiveMemoryWarning
{
UIAlertView *alertDialog;
alertDialog = [[UIAlertView alloc]
initWithTitle:NSLocalizedString(#"Memory Problem", #"Hafıza Problemi")
message: NSLocalizedString(#"Please Close Some Applications!", #"Hafıza Problemi")
delegate: nil
cancelButtonTitle: #"Ok"
otherButtonTitles: nil];
[alertDialog show];
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#end
Related
please try to help me here I have some really weird bug(s) trying to sort my string table view objects.
The behaviour is simple, I have:
CreateViewController - here I create strings and add them to core data
StackTableViewController - this is the table view for the strings I create. They should be sorted by date, the first cell is the oldest, the second cell created after him and so on...
HomeViewController - here I have a UILabel that holds the first object of the table view all the time, if I delete it in the table I update this label with a delegate method,
So this is it.
The problem:
If there is NO strings in the table view and then I add a string in the create page, it gets created fine, but if add another one , the new one is at top of the list...but if I terminate the app and open it again the order is fine.
there are also some other weird behaviour after I add more strings...But the thing is, whenever I terminate the app and open it again everything is ordered perfectly..:/
This is the relevant code:
CreateViewController.m
- (id)init {
self = [super initWithNibName:#"CreateViewController" bundle:nil];
if (self) {
}
return self;
}
- (void)save {
if (self.myTextView.text.length == 0) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Hey!" message:#"You can't save a blank string" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
[self insertTeget];
[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
[self.myTextView resignFirstResponder];
}
//this is where I add the string to the NSManagedObject object I have called 'Target'
- (void)insertTeget {
CoreDataStack *stack = [CoreDataStack defaultStack];
Target *target = [NSEntityDescription insertNewObjectForEntityForName:#"Target" inManagedObjectContext:stack.managedObjectContext];
if (self.myTextView.text != nil) {
target.body = self.myTextView.text;
}
[stack saveContext];
}
This is the table view:
StackTableViewController.m
- (id)init {
self = [super initWithNibName:#"StackTableViewController" bundle:nil];
if (self) {
[self fetchData];
}
return self;
}
//currentTarget is a string I have in the .h file to pass the home view controller the first string of the table view
- (void)fetchData {
[self.fetchedResultController performFetch:nil];
if (self.fetchedResultController.fetchedObjects.count > 0) {
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
self.currentTarget = current.body;
}else {
self.currentTarget = nil;
}
}
- (void)viewDidLoad {
[super viewDidLoad];
[self fetchData];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return self.fetchedResultController.sections.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultController sections][section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
//here I'm updating the delegate when A cell was deleted so I can update the label in the home view controller
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
Target *target = [self.fetchedResultController objectAtIndexPath:indexPath];
CoreDataStack *stack = [CoreDataStack defaultStack];
[[stack managedObjectContext] deleteObject:target] ;
[stack saveContext];
if ([_delegate respondsToSelector:#selector(didDeleteObject)]) {
[self fetchData];
[_delegate didDeleteObject];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"StackTableViewCell";
Target *target = [self.fetchedResultController objectAtIndexPath:indexPath];
StackTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"StackTableViewCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
cell.cellLabel.text = target.body;
return cell;
}
// this is my fetch request where im setting up the sort descriptor
- (NSFetchRequest *)targetsFetchRequest {
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Target"];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"time" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
return fetchRequest;
}
- (NSFetchedResultsController *)fetchedResultController {
if (_fetchedResultController != nil) {
return _fetchedResultController;
}
CoreDataStack *stack = [CoreDataStack defaultStack];
NSFetchRequest *fetchRequest = [self targetsFetchRequest];
_fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:stack.managedObjectContext sectionNameKeyPath:nil cacheName:nil];
_fetchedResultController.delegate = self;
return _fetchedResultController;
}
This is the home view controller where Im updating the label:
- (id)init {
self = [super initWithNibName:#"HomeViewController" bundle:nil];
if (self) {
stackTableViewController = [[StackTableViewController alloc] init];
stackTableViewController.delegate = self;
}
return self;
}
- (void)viewWillAppear:(BOOL)animated {
[stackTableViewController fetchData];
self.homeLabel.text = stackTableViewController.currentTarget;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.homeLabel.text = stackTableViewController.currentTarget;
}
//this is the delegate method
- (void)didDeleteObject {
self.homeLabel.text = stackTableViewController.currentTarget;
}
- (IBAction)goToStack:(id)sender {
[self.navigationController pushViewController:stackTableViewController animated:YES];
}
- (IBAction)goToCreate:(id)sender {
CreateViewController *createViewController = [[CreateViewController alloc]initWithNibName:#"CreateViewController" bundle:nil];
UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:createViewController];
[self.navigationController presentViewController:navigationController animated:YES completion:nil]}
Please please please, it's driving me crazy, why the order is fine only after i terminate the app?
thanks###!
I don't see you setting time anywhere. It should be set to [NSDate date] when you create the object, if it's acting as a creation date.
I'm trying to implement a UISearchBar in a custom UITableViewController and done programmatically (not using IB). I got the search function to work and return the correct fields, but it is displaying the searched cells over the full list cells:
As you can see, the new searched field is scrollable and selectable. Its just not removing the old cells.
here is my .h file:
#interface TestTableViewController : UITableViewController <UISearchBarDelegate, UISearchDisplayDelegate>
#property (strong, nonatomic) NSArray *boundaries;
#end
.m file:
#import "TestTableViewController.h"
#import "Boundary.h"
#interface TestTableViewController ()
#property (strong, nonatomic) UISearchDisplayController *searchController;
#property (strong, nonatomic) NSMutableArray *filteredBoundaries;
#end
#implementation TestTableViewController
-(instancetype) initWithStyle:(UITableViewStyle)style {
self = [super initWithStyle:style];
if (self) {
self.filteredBoundaries = [NSMutableArray array];
}
return self;
}
-(void)viewDidLoad {
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:TRUE selector:#selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors = #[sortDescriptor];
self.boundaries = [self.boundaries sortedArrayUsingDescriptors:sortDescriptors];
UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];
searchBar.delegate = self;
searchBar.placeholder = #"Search Fields";
searchBar.showsCancelButton = TRUE;
self.tableView.tableHeaderView = searchBar;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
self.searchController.delegate = self;
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Setup Filter Data Source
-(void)filterContentForSearchText:(NSString *)searchText scope:(NSString *)scope {
[self.filteredBoundaries removeAllObjects];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name contains[c] %#", searchText];
self.filteredBoundaries = [NSMutableArray arrayWithArray:[self.boundaries filteredArrayUsingPredicate:predicate]];
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark Table view data source
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (tableView == self.searchDisplayController.searchResultsTableView) {
return self.filteredBoundaries.count;
}
else {
return self.boundaries.count;
}
}
-(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];
}
if (tableView == self.searchDisplayController.searchResultsTableView) {
Boundary *boundary = [self.filteredBoundaries objectAtIndex:indexPath.row];
cell.textLabel.text = boundary.name;
cell.textLabel.textColor = [UIColor blackColor];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
}
else {
Boundary *boundary = [self.boundaries objectAtIndex:indexPath.row];
cell.textLabel.text = boundary.name;
cell.textLabel.textColor = [UIColor blackColor];
cell.selectionStyle = UITableViewCellSelectionStyleBlue;
cell.userInteractionEnabled = TRUE;
}
return cell;
}
// ------------------------------------------------------------------------------------------------------
#pragma mark -
#pragma mark UISearchDisplayController Delegates
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:[[self.searchController.searchBar scopeButtonTitles] objectAtIndex:self.searchController.searchBar.selectedScopeButtonIndex]];
return TRUE;
}
#end
And how I call the table view:
TestTableViewController *tableViewController = [[TestTableViewController alloc] initWithStyle:UITableViewStylePlain];
tableViewController.boundaries = [group.boundaries allObjects];
tableViewController.contentSizeForViewInPopover = POPOVER_SIZE;
UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:tableViewController];
navController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
navController.navigationBar.barStyle = UIBarStyleBlack;
self.myPopoverController = [[UIPopoverController alloc] initWithContentViewController:navController];
self.myPopoverController.delegate = self;
[self.myPopoverController presentPopoverFromRect:button.frame inView:button.superview permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
Any ideas what I might be doing wrong or missing?
The problem is that UISearchDisplayController is using another UITableView rather than the view controller's own. You can verify that by logging tableView in -tableView:cellForRowAtIndexPath:.
You can use a UISearchBar without a UISearchDisplayController, to have more control over search and display logic.
Also, if your app doesn't support any version prior to iOS 8, consider using UISearchController. I haven't tried it but it seems to give you more control. Check a sample UISearchDisplayControllerhas been deprecated in iOS 8.
Try this
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, 320.0, 41.0)];
[self.view addSubview:searchBar];
searchBar.delegate=self;
- (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.
if (isSearching) {
return [filteredContentList count];
}
else {
return [titlearray count];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"SimpleTableCell";
SimpleTableCell *cell = (SimpleTableCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"SimpleTableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (isSearching)
{
cell.nameLabel.text = [filteredContentList objectAtIndex:indexPath.row];
cell.thumbnailImageView.image =[filteredImgArray objectAtIndex:indexPath.row];
}
else
{
cell.thumbnailImageView.image = [imagearray objectAtIndex:indexPath.row];
cell.nameLabel.text = [titlearray objectAtIndex:indexPath.row];
}
return cell;
}
- (void)searchTableList {
NSString *searchString = searchBar.text;
for (int i=0; i<titlearray.count; i++) {
NSString *tempStr=[titlearray objectAtIndex:i];
NSComparisonResult result = [tempStr compare:searchString options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchString length])];
if (result == NSOrderedSame)
{
[filteredContentList addObject:tempStr];
[filteredImgArray addObject:[imagearray objectAtIndex:i]];
}
}
}
#pragma mark - Search Implementation
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
isSearching = YES;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
NSLog(#"Text change - %d",isSearching);
//Remove all objects first.
[filteredContentList removeAllObjects];
[filteredImgArray removeAllObjects];
if([searchText length] != 0) {
isSearching = YES;
[self searchTableList];
//tblContentList.hidden=NO;
}
else {
isSearching = NO;
// tblContentList.hidden=YES;
}
[tblContentList reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Cancel clicked");
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
NSLog(#"Search Clicked");
[self searchTableList];
}
I hope it's help for you
You should implement correct datasource.
Create new array of items for filtered data for first.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSInteger count = ([filteredItems count] > 0) ? [filteredItems count] : [self.allItems count];
return count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier: #"id"];
MyCustomItem *item = ([filteredItems count] > 0) ? filteredItems[indexPath.row] : self.allItems[indexPath.row];
[self configureCell:cell forItem:item];
return cell;
}
Configure searching:
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchText = searchController.searchBar.text;
if ([searchText length] == 0)
{
[filteredItems removeAllObjects];
[self.tableView reloadData];
return;
}
NSMutableArray *searchResults = [self.allItems mutableCopy];
// SKIP ALL BODY OF SEARCHING
filteredPeoples = searchResults;
[self.tableView reloadData];
}
Will work pretty.
IOS 8 delegate has been deprecated not sure if that's the problem.
The method
here's [a link]https://developer.apple.com/Library/ios/documentation/UIKit/Reference/UISearchDisplayDelegate_Protocol/index.html#//apple_ref/occ/intfm/UISearchDisplayDelegate/searchDisplayControS 8 delegate has been deprecated not sure if that's the problem.
The method
try this property instead
#property(nonatomic, assign) id< UISearchResultsUpdating > searchResultsUpdater
another better link [a link]https://developer.apple.com/library/ios/samplecode/TableSearch_UISearchController/Listings/TableSearch_obj_c_TableSearch_APLResultsTableController_m.html
I am trying to display data in a custom tableview. Idea is that in ViewController A i populate data into the Core Data entity, in ViewController B I retrieve data from Core Data entity successfully and display it in table view with no problem. Here comes the problem. If I delete data from entity and tableview in ViewController B, go back to ViewController A and add new item to Core Data again, it does not appear in tableview when I go back to ViewController B. But if i close and open the application again, the item appears there again.
So the problem is that the item appear in core data after deleting an item and inserting again, but doesnt appear in tableview. Maybe i have to update tableview somehow, but i tried [self.tableview reloadData]; and it did not help. Code Below. Any Ideas???
ViewController A
#import "ListItem.h"
#import "ViewOrders.h"
#import "MainView.h"
#import "Order_list.h"
#import "AppDelegate.h"
#interface ListItem ()
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain) NSFetchedResultsController *results;
#property (nonatomic, strong) NSMutableArray *namesArray;
#property (nonatomic, strong) NSMutableArray *quantityArray;
#property (nonatomic, strong) NSMutableArray *priceArray;
#property (nonatomic, strong) NSMutableArray *imagesArray;
#end
#implementation ListItem
#synthesize managedObjectContext = _managedObjectContext;
#synthesize results = _results;
#synthesize imageView = _imageView;
#synthesize mainView = _mainView;
#synthesize nameField = _nameField;
#synthesize descField = _descField;
#synthesize priceField = _priceField;
#synthesize quantityField = _quantityField;
#synthesize quantityStepperOutlet = _quantityStepperOutlet;
#synthesize namesArray =_namesArray;
#synthesize quantityArray = _quantityArray;
#synthesize priceArray = _priceArray;
#synthesize imagesArray = _imagesArray;
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = delegate.managedObjectContext;
//self.navigationItem.hidesBackButton = YES;
self.namesArray = [[NSMutableArray alloc] init];
self.quantityArray = [[NSMutableArray alloc] init];
self.priceArray = [[NSMutableArray alloc] init];
self.imagesArray = [[NSMutableArray alloc] init];
UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:#"bella_italia_crop.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.view.backgroundColor = [UIColor colorWithPatternImage:image];
UIGraphicsBeginImageContext(self.mainView.frame.size);
[[UIImage imageNamed:#"bella_italia_crop.png"] drawInRect:self.mainView.bounds];
UIImage *image2 = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
self.mainView.backgroundColor = [UIColor colorWithPatternImage:image2];
self.imageView.image = [UIImage imageNamed:self.thumbnail];
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
self.nameField.text = self.name;
self.descField.text = self.description;
self.priceField.text = self.price;
self.descField.backgroundColor = [UIColor clearColor];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"viewAllOrdersSegue"])
{
ViewOrders *vo = segue.destinationViewController;
vo.namesArray = self.namesArray;
vo.quantityArray = self.quantityArray;
vo.priceArray = self.priceArray;
vo.tableNumber = #"1";
vo.imagesArray = self.imagesArray;
}
else if ([segue.identifier isEqualToString:#"unwindToMain"])
{
MainView *mv = segue.destinationViewController;
mv.namesArray = self.namesArray;
mv.quantityArray = self.quantityArray;
mv.priceArray = self.priceArray;
mv.imagesArray = self.imagesArray;
}
}
- (IBAction)quantityStepper:(UIStepper *)sender
{
int stepper = [sender value];
self.quantityField.text = [NSString stringWithFormat:#"%d", stepper];
}
- (IBAction)addOrderAction:(UIButton *)sender
{
NSLog(#"Add order action button pressed");
Order_list *newItem = [NSEntityDescription insertNewObjectForEntityForName:#"Order_list" inManagedObjectContext:self.managedObjectContext];
newItem.title = self.name;
newItem.quantity = #([self.quantityField.text floatValue]);
newItem.price = #([self.priceField.text floatValue]);
newItem.tableNumber = [NSNumber numberWithInt:1];
newItem.thumbnail = self.thumbnail;
newItem.id = [NSNumber numberWithInt:0];
NSError *error;
[self.managedObjectContext save:&error];
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:#"Success!" message:#"Your order was successfully added to orders list! Press View Orders to finalize the order or go back to menu and choose something else." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
successAlert.alertViewStyle = UIAlertViewStyleDefault;
[successAlert show];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Order_list" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObjectContext *info in fetchedObjects) {
NSLog(#"Title: %# %#", [info valueForKey:#"title"], [info valueForKey:#"quantity"]);
}
//[self.namesArray addObject:self.name];
//[self.quantityArray addObject:self.quantityField.text];
//int finalPrice = [self.quantityField.text intValue] * [self.price intValue];
//[self.priceArray addObject:[NSString stringWithFormat:#"%d", finalPrice]];
//[self.imagesArray addObject:self.thumbnail];
//NSLog(#"Names: %#, Quantities: %#, Prices: %#", self.namesArray, self.quantityArray, self.priceArray);
}
#end
ViewController B
#import "ViewOrders.h"
#import "AppDelegate.h"
#import "Order_list.h"
#import "ViewOrdersCell.h"
#interface ViewOrders ()
#property (nonatomic, strong) NSMutableData *requestData;
#property (nonatomic, strong) NSManagedObjectContext *managedObjectContext;
#property (nonatomic, retain) NSFetchedResultsController *results;
#property (nonatomic, strong) NSString* orderState;
#property (nonatomic, strong) UIAlertView *billAlert;
#end
#implementation ViewOrders
#synthesize managedObjectContext = _managedObjectContext;
#synthesize results = _results;
#synthesize confirmOrderButton = _confirmOrderButton;
#synthesize requestData = _requestData;
#synthesize orderState = _orderState;
#synthesize billAlert = _billAlert;
- (void)viewDidLoad
{
[super viewDidLoad];
self.billAlert = [[UIAlertView alloc] initWithTitle:#"Order Confirmed!" message:#"Your order list has been successfully confirmed and is sent to kitchen! Press Request Bill Now or Request Bill Later to Continue (You cannot make any new orders until you request a bill for current one! To trigger this screen again, press and hold on any order in pending orders page. Thanks!)" delegate:self cancelButtonTitle:#"Request Bill Later" otherButtonTitles:#"Request Bill Now", nil];
self.billAlert.tag = 2;
self.billAlert.alertViewStyle = UIAlertViewStyleDefault;
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = delegate.managedObjectContext;
self.namesArray = [[NSMutableArray alloc] init];
self.quantityArray = [[NSMutableArray alloc] init];
self.imagesArray = [[NSMutableArray alloc] init];
self.priceArray = [[NSMutableArray alloc] init];
NSFetchRequest *coreRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Order_list" inManagedObjectContext:self.managedObjectContext];
[coreRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"title" ascending:YES];
[coreRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[coreRequest setFetchBatchSize:20];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:coreRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
self.results = controller;
self.results.delegate = self;
NSError *error;
[self.results performFetch:&error];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:coreRequest error:&error];
for (NSManagedObjectContext *info in fetchedObjects)
{
self.orderState = [NSString stringWithFormat:#"%#", [info valueForKey:#"id"]];
[self.namesArray addObject:[info valueForKey:#"title"]];
[self.quantityArray addObject:[info valueForKey:#"quantity"]];
[self.imagesArray addObject:[info valueForKey:#"thumbnail"]];
[self.priceArray addObject:[info valueForKey:#"price"]];
//NSLog(#"List: %#", [info valueForKey:#"title"]);
}
if ([self.orderState isEqualToString:#"1"])
{
self.confirmOrderButton.enabled = false;
}
//self.navigationController.navigationItem.backBarButtonItem.enabled = false;
//self.navigationItem.hidesBackButton = YES;
// 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)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id sectionInfo = [[self.results sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ordersCell" forIndexPath:indexPath];
ViewOrdersCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ordersCell" forIndexPath:indexPath];
cell.title.text = [self.namesArray objectAtIndex:indexPath.row];
cell.thumbnail.image = [UIImage imageNamed:[self.imagesArray objectAtIndex:indexPath.row]];
cell.status.text = #"Waiting to Confirm";
if ([self.orderState isEqualToString:#"0"])
{
cell.status.text = #"Waiting to Confirm";
cell.status.textColor = [UIColor redColor];
}
else
{
cell.status.textColor = [UIColor greenColor];
cell.status.text = #"Confirmed";
}
UILongPressGestureRecognizer *longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:#selector(onLongPress:)];
[cell addGestureRecognizer:longPressRecognizer];
//cell.textLabel.text = [self.namesArray objectAtIndex:indexPath.row];
//cell.imageView.image = [UIImage imageNamed:[self.imagesArray objectAtIndex:indexPath.row]];
//cell.backgroundColor = [UIColor clearColor];
return cell;
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
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
NSManagedObject *managedObject = [self.results objectAtIndexPath:indexPath];
[self.managedObjectContext deleteObject:managedObject];
[self.managedObjectContext save:nil];
//[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
//[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (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 {
if (type == NSFetchedResultsChangeInsert)
{
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
}
if (type == NSFetchedResultsChangeDelete)
{
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
if (type == NSFetchedResultsChangeUpdate)
{
}
if (type == NSFetchedResultsChangeMove)
{
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id<NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
if (type == NSFetchedResultsChangeInsert)
{
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
}
if (type == NSFetchedResultsChangeDelete)
{
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
}
}
/*
// 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 - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 1 && alertView.tag == 1)
{
NSLog(#"Confirm Pressed");
//////Send Order to the Server//////
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Order_list"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"id=0"];
fetchRequest.predicate = predicate;
NSError *error = nil;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObjectContext *info in array)
{
NSNumber *temp = [[NSNumber alloc] initWithInt:1];
[info setValue:temp forKey:#"id"];
}
[self.managedObjectContext save:&error];
[self.tableView reloadData];
self.confirmOrderButton.enabled = false;
[self.billAlert show];
}
else if (buttonIndex == 1 && alertView.tag == 2)
{
self.confirmOrderButton.enabled = true;
UIAlertView *billRequest = [[UIAlertView alloc] initWithTitle:#"Bill Request Successful!" message:#"Your bill has been requested successfully! Waiter will deliver it to you as soon as possible! Thanks for visiting Bella Italia!" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
billRequest.alertViewStyle = UIAlertViewStyleDefault;
billRequest.tag = 3;
[billRequest show];
NSFetchRequest *fetchItems = [[NSFetchRequest alloc] init];
[fetchItems setEntity:[NSEntityDescription entityForName:#"Order_list" inManagedObjectContext:self.managedObjectContext]];
[fetchItems setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *array = [self.managedObjectContext executeFetchRequest:fetchItems error:&error];
[self.results performFetch:&error];
//error handling goes here
for (NSManagedObject *item in array)
{
[self.managedObjectContext deleteObject:item];
}
NSError *saveError = nil;
[self.managedObjectContext save:&saveError];
}
else if (buttonIndex == 0 && alertView.tag == 2)
{
}
else if (buttonIndex == 0 && alertView.tag == 3)
{
[self.navigationController popToRootViewControllerAnimated:UITableViewRowAnimationFade];
}
}
- (IBAction)confirmOrder:(UIBarButtonItem *)sender
{
NSLog(#"Confirm Order");
UIAlertView *confOrder = [[UIAlertView alloc] initWithTitle:#"Confirm Order!" message:#"This will send your order to process. Once this is done, no more changes are available. Are you sure you want to confirm your order?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Confirm", nil];
confOrder.alertViewStyle = UIAlertViewStyleDefault;
confOrder.tag = 1;
[confOrder show];
}
-(void)onLongPress:(UILongPressGestureRecognizer*)pGesture
{
NSLog(#"Long Press");
[self.billAlert show];
}
#end
EDIT
Forgot to mention that i am using Custom Cell. Maybe that affects the situation somehow?
I tried to NSLog the variables which store the data that supposed to appear in tableview. All the data is beeing passed, but it does not appear in tableview. Logically [self.tableView reloadData in viewWillAppear should do the trick, but it does not........
I have a similar setup in one my apps and I add an observer to the ViewController with the table that wants updating;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reload) name:#"UpdatedCoreData" object:nil];
I clear any arrays or dictionaries I use in the reload method and call (inside my async queue);
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
Then when I finish updating the core data in my other VC I call it;
[[NSNotificationCenter defaultCenter] postNotificationName:#"UpdatedCoreData" object: nil];
And that works perfectly fine for me, I don't know if that will help you at all.
EDIT:
Along the lines of my reload method;
- (void)reload {
// Do any potential clean up if neccesary
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
// Fetch core data & populate dictionaries/arrays
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
});
}
I have found the way I need to implement a sections collapsable/expandible tableView, but it is populating the row object from the code itself. I have just created a core data entity and want know to populate the row objects with it.
I have also include a NSFetchedResultsController, but I need help converting this particular code to let me add core data objects. This is my current code:
#import "CollapsableTableViewViewController.h"
#import "CollapsableTableView.h"
#import "CollapsableTableViewAppDelegate.h"
#interface CollapsableTableViewViewController()
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#end
#implementation CollapsableTableViewViewController
#synthesize fetchedResultsController = _fetchedResultsController;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//1
CollapsableTableViewAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//2
self.managedObjectContext = appDelegate.managedObjectContext;
self.fetchedResultsController = nil;
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
CollapsableTableView* tableView = (CollapsableTableView*) myTableView;
tableView.collapsableTableViewDelegate = self;
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"First Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Second Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Third Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Fourth Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Fifth Section"];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
- (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.
}
- (void)viewDidUnload {
[spinner release];
spinner = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[spinner release];
[super dealloc];
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 10;
}
+ (NSString*) titleForHeaderForSection:(int) section
{
switch (section)
{
case 0 : return #"First Section";
case 1 : return #"Second Section";
case 2 : return #"Third Section";
case 3 : return #"Fourth Section";
case 4 : return #"Fifth Section";
default : return [NSString stringWithFormat:#"Section no. %i",section + 1];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [CollapsableTableViewViewController titleForHeaderForSection:section];
}
// Uncomment the following two methods to use custom header views.
//- (UILabel *) createHeaderLabel: (UITableView *) tableView :(NSString *)headerTitle {
// UILabel *titleLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
// titleLabel.frame =CGRectMake(0, 0, tableView.frame.size.width - 20, 60);
// titleLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
// titleLabel.backgroundColor = [UIColor clearColor];
// titleLabel.textColor = [UIColor whiteColor];
// titleLabel.font=[UIFont fontWithName:#"Helvetica-Bold" size:20];
// titleLabel.text = headerTitle;
// titleLabel.textAlignment = UITextAlignmentRight;
// return titleLabel;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
// // create the parent view that will hold header Label
// UIView * customView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.frame.size.width , 60)]autorelease];
// UILabel *titleLabel;
// titleLabel = [self createHeaderLabel: tableView :[CollapsableTableViewViewController titleForHeaderForSection:section]];
//
// [customView addSubview:titleLabel];
//
// UILabel* collapsedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10,0,50,60)] autorelease];
// collapsedLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
// collapsedLabel.backgroundColor = [UIColor clearColor];
// collapsedLabel.textColor = [UIColor whiteColor];
// collapsedLabel.text = #"-";
// collapsedLabel.tag = COLLAPSED_INDICATOR_LABEL_TAG;
// [customView addSubview:collapsedLabel];
//
// customView.tag = section;
// customView.backgroundColor = [UIColor blackColor];
// return customView;
//}
//- (NSString*) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
//{
// return [NSString stringWithFormat:#"Footer %i",section + 1];
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section)
{
case 2 : return 0;
case 3 : return 30;
default : return 8;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
switch (indexPath.row)
{
case 0 : cell.textLabel.text = #"First Cell"; break;
case 1 : cell.textLabel.text = #"Second Cell"; break;
case 2 : cell.textLabel.text = #"Third Cell"; break;
case 3 : cell.textLabel.text = #"Fourth Cell"; break;
case 4 : cell.textLabel.text = #"Fifth Cell"; break;
case 5 : cell.textLabel.text = #"Sixth Cell"; break;
case 6 : cell.textLabel.text = #"Seventh Cell"; break;
case 7 : cell.textLabel.text = #"Eighth Cell"; break;
default : cell.textLabel.text = [NSString stringWithFormat:#"Cell %i",indexPath.row + 1];
}
//cell.detailTextLabel.text = ...;
return cell;
}
#pragma mark -
#pragma mark CollapsableTableViewDelegate
- (void) collapsableTableView:(CollapsableTableView*) tableView willCollapseSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner startAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView didCollapseSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner stopAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView willExpandSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner startAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView didExpandSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner stopAnimating];
}
#pragma mark -
#pragma mark IBAction methods
- (IBAction) toggleSection2
{
NSString* sectionTitle = //[NSString stringWithFormat:#"Tag %i",1]; // Use this expression when using custom header views.
[CollapsableTableViewViewController titleForHeaderForSection:1]; // Use this expression when specifying text for headers.
CollapsableTableView* collapsableTableView = (CollapsableTableView*) myTableView;
BOOL isCollapsed = [[collapsableTableView.headerTitleToIsCollapsedMap objectForKey:sectionTitle] boolValue];
[collapsableTableView setIsCollapsed:! isCollapsed forHeaderWithTitle:sectionTitle];
}
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"ToDoItems" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:#"tdText" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil
cacheName:#"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
#end
One way to do this is by storing the objects that you fetched into an Array or dictionary and later moving it into cell.
For example, declare NSArray *fetchedResults in your .h file. Then store fetched results into this array as shown below.
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
*fetchedResults = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
Later, fill your uitableviewcell rows from the array
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
// Replacing switch with below code will populate your cell rows in the order in which data is retrieved from core data.
cell.textLabel.text = [self.fetchedResults objectAtIndex:(indexPath.row)] ;
......
......
}
You can add your own logic to get correct content into each rows.
I have a mutable Array in a Tableview, this is populated on View did load from an SQLite database, However this database changes as it is a favourites database for products in my app.
When a user selects one of the items in the tableview (The user then goes to a detail view, with the info from the database) the user can then select to remove it from the favourites (database) when the user then presses back in the navigation bar, the item is still there, I've tried tableview reload on view did appear, and view will appear but that doesn't help,
Can anyone shed any light on this??
Many thanks,
Andrew
Here is my code:
FavTableViewController.h:
#interface FavTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> {
IBOutlet UITableView *Table;
}
#property (nonatomic, strong) UITableView *Table;
#property (nonatomic, strong) NSArray *cats;
#property (nonatomic, strong) IBOutlet UISearchBar *searchBar;
#property (nonatomic, strong) UISearchDisplayController *searchDisplayController;
#property (nonatomic, strong) NSMutableArray *filteredListContent;
#property (nonatomic, strong) NSMutableArray *listContent;
#property (nonatomic, strong) NSArray *everything;
#property (nonatomic, copy) NSString *savedSearchTerm;
#property (nonatomic) NSInteger savedScopeButtonIndex;
#property (nonatomic) BOOL searchWasActive;
#property (nonatomic, strong) NSString *cellText;
-(void) refresh;
#end
FavTableViewController.m:
#import "FavTableViewController.h"
#import "DBFavAdapter.h"
#import "MenuData.h"
#import "DBAdapter.h"
#import "DetailViewController.h"
#import "ConsoleDetailController.h"
#import "EffectDetailViewController.h"
#import "DimmersDetailController.h"
#import "ConventionalController.h"
#import "ProDetailViewController.h"
#implementation FavTableViewController
#synthesize filteredListContent, savedSearchTerm, savedScopeButtonIndex, searchWasActive, searchBar, searchDisplayController, listContent, everything, cellText, cats, Table;
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
listContent = [[NSMutableArray alloc] init];
}
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 {
NSLog(#"Did Load");
[super viewDidLoad];
everything = [[DBFavAdapter allProducts] mutableCopy];
for (NSDictionary *dict in everything) {
[listContent addObject: [dict objectForKey:#"Title"]];
}
// create a filtered list that will contain products for the search results table.
self.filteredListContent = [NSMutableArray arrayWithCapacity:[self.listContent count]];
// restore search settings if they were saved in didReceiveMemoryWarning.
if (self.savedSearchTerm)
{
[self.searchDisplayController setActive:self.searchWasActive];
[self.searchDisplayController.searchBar setSelectedScopeButtonIndex:self.savedScopeButtonIndex];
[self.searchDisplayController.searchBar setText:savedSearchTerm];
self.savedSearchTerm = nil;
}
// [self.tableView reloadData];
self.Table.scrollEnabled = YES;
self.navigationItem.title = #"Favourites";
// cats = [DBFavAdapter allCategories];
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.filteredListContent = nil;
NSLog(#"Unload");
}
- (void)viewWillAppear:(BOOL)animated {
NSLog(#"View will Appear");
[Table reloadData];
NSLog(#"Everything: %#",everything);
NSLog(#"list Content: %#",listContent);
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
NSLog(#"View did Appear");
[super viewDidAppear:animated];
NSLog(#"list Content appeared: %#",listContent);
[Table reloadData];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
NSLog(#"Did dissapear");
// save the state of the search UI so that it can be restored if the view is re-created
self.searchWasActive = [self.searchDisplayController isActive];
self.savedSearchTerm = [self.searchDisplayController.searchBar text];
self.savedScopeButtonIndex = [self.searchDisplayController.searchBar selectedScopeButtonIndex];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(tableView == self.searchDisplayController.searchResultsTableView){
return [self.filteredListContent count];
}
else {
return [self.listContent count];
}
NSLog(#"Rows %i",[self.listContent count]);
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// NSDictionary *dictionary = [self.tableDataSource objectAtIndex:indexPath.row];
if (tableView == searchDisplayController.searchResultsTableView)
{
cellText = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
cellText = [self.listContent objectAtIndex:indexPath.row];
}
// NSString *cellText = [self.listContent objectAtIndex:indexPath.row];
UIFont *cellFont = [UIFont fontWithName:#"Heiti TC" size:17.0];
CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
CGSize labelSize = [cellText sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
return labelSize.height + 30;
}
- (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath {
NSUInteger row = 1;
return row;
}
- (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.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
cell.textLabel.font = [UIFont fontWithName:#"Heiti TC" size:17.0];
}
// Configure the cell...
if (tableView == searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = [self.listContent objectAtIndex:indexPath.row];
}
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *selectedItem;
if (tableView == self.searchDisplayController.searchResultsTableView)
{
selectedItem = [self.filteredListContent objectAtIndex:indexPath.row];
}
else
{
selectedItem = [self.listContent objectAtIndex:indexPath.row];
}
// Is the selection a category?
// NSArray *cats = [DBAdapter allCategories];
__block BOOL cat = NO;
[cats enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([(NSString*)obj isEqualToString:selectedItem]) {
cat = YES;
*stop = YES;
}
}];
if (cat) { // the user's selection was a category
// NSLog(#"Selected item was a category");
}
else {
NSArray *mans = [DBAdapter allManufacturers];
__block BOOL man = NO;
[mans enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([(NSString*)obj isEqualToString:selectedItem]) {
man = YES;
*stop = YES;
}
}];
if (man) { // the user's selection was a manufacturer
// NSLog(#"Selected item was a manufacturer");
} else {
// the user's selection was a product
// Find selectedItem in products
__block NSDictionary *selectedRow = nil;
[self.everything enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
//everything is an array of dictionaries
if ([(NSString*)[(NSDictionary*)obj objectForKey:#"Title"] isEqualToString:selectedItem]) {
selectedRow = (NSDictionary*)obj;
*stop = YES;
}
}];
MenuData *selectionData = [MenuData menuData];
selectionData.manufacturerID = [[selectedRow objectForKey:#"Manufacturer_id"] integerValue];
selectionData.categoryID = [[selectedRow objectForKey:#"Category_id"] integerValue];
selectionData.sCategoryID = [[selectedRow objectForKey:#"SubCategory_id"] integerValue];
selectionData.ssCategoryID = [[selectedRow objectForKey:#"SuperSubCategory_id"] integerValue];
NSString *selectedTitle = [selectedRow objectForKey: #"Title"]; // You probably already have this value from your search. Here for the sake of clarity.
NSDictionary *productDetails = [DBAdapter productDetails: selectedTitle forCurrentData: selectionData];
NSArray *allKeys = [productDetails allKeys];
// NSLog(#"values: %i", [allKeys count]);
for (NSString *key in allKeys) {
id value = [productDetails objectForKey:key];
if ([value isKindOfClass:[NSString class]]) {
// NSLog(#"key: %# value: %#", key, value);
}
}
NSInteger ViewNumber = [[productDetails objectForKey:#"View"] integerValue];
switch (ViewNumber) {
case 25: {
DetailViewController *dvController = [[DetailViewController alloc] initWithNibName:#"DetailView" bundle:[NSBundle mainBundle]];
dvController.dictionary = productDetails;
[self.navigationController pushViewController:dvController animated:YES];
}
break;
case 18: {
EffectDetailViewController *edvController = [[EffectDetailViewController alloc] initWithNibName:#"EffectDetailView" bundle:[NSBundle mainBundle]];
edvController.dictionary = productDetails;
[self.navigationController pushViewController:edvController animated:YES];
}
break;
case 17: {
ConsoleDetailController *cdvController = [[ConsoleDetailController alloc] initWithNibName:#"ConsoleDetailController" bundle:[NSBundle mainBundle]];
cdvController.dictionary = productDetails;
[self.navigationController pushViewController:cdvController animated:YES];
}
break;
case 2: {
ConsoleDetailController *cdvController = [[ConsoleDetailController alloc] initWithNibName:#"ConsoleDetailController" bundle:[NSBundle mainBundle]];
cdvController.dictionary = productDetails;
[self.navigationController pushViewController:cdvController animated:YES];
}
break;
case 3: {
DimmersDetailController *ddvController = [[DimmersDetailController alloc] initWithNibName:#"DimmersDetailController" bundle:[NSBundle mainBundle]];
ddvController.dictionary = productDetails;
[self.navigationController pushViewController:ddvController animated:YES];
}
break;
case 12: {
ConventionalController *cController = [[ConventionalController alloc] initWithNibName:#"ConventionalController" bundle:[NSBundle mainBundle]];
cController.dictionary = productDetails;
[self.navigationController pushViewController:cController animated:YES];
}
break;
case 5: {
ProDetailViewController *pController = [[ProDetailViewController alloc] initWithNibName:#"ProDetailViewController" bundle:[NSBundle mainBundle]];
pController.dictionary = productDetails;
[self.navigationController pushViewController:pController animated:YES];
}
break;
}
}
}
}
#pragma mark -
#pragma mark Content Filtering
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope {
/*
Update the filtered array based on the search text and scope.
*/
[self.filteredListContent removeAllObjects]; // First clear the filtered array.
/*
Search the main list for products whose type matches the scope (if selected) and whose name matches searchText; add items that match to the filtered array.
*/
for (NSString *product in listContent)
{
//Edit AD - NS Range works instead of NSComparisonResult
NSRange result = [product rangeOfString:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch)];
if (result.location != NSNotFound)
{
[self.filteredListContent addObject:product];
}
/*
// NSComparisonResult result = [product compare:searchText options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [searchText length])];
if (result == NSOrderedSame)
{
[self.filteredListContent addObject:product];
}
*/
}
}
#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString {
[self filterContentForSearchText:searchString scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption {
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:
[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
// Return YES to cause the search result table view to be reloaded.
return YES;
}
- (void)refresh {
NSLog(#"Refresh");
if([NSThread isMainThread])
{
[self.Table reloadData];
[self.Table setNeedsLayout];
[self.Table setNeedsDisplay];
}
else
{
[self performSelectorOnMainThread:#selector(refresh) withObject:nil waitUntilDone:YES];
}
}
#end
You have 2 options.
Remove the item from the listContent as well. This can be done via a delegate method that will be called from the child view controller when you delete the item.
Move your viewDidLoad functionality where listContents is generated from the database to viewWillAppear. This will cause listContents to read the database again, after the item was deleted and you hit the back button, this will also get called when the view first opens.