How to implement searchbar in iOS 7 tableView? - ios

I'm new to programming. I am building a program that scans barcodes and puts the UPC number in the search box in my table view. Now all i want to do is create a search for the UPC scanned. the viewTable is displaying an inventory from a sqlite database.
The search bar is built all i need to do is program it to search, and I have not found any good tutorials on how to do this. How can I implement this?
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "ScanViewController.h"
#import <sqlite3.h>
#interface MasterViewController ()
{
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
{
}
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Get the DBAccess object;
DBAccess *dbAccess = [[DBAccess alloc] init];
// Get the products array from the database
self.products = [dbAccess getAllProducts];
// Close the database because we are finished with it
[dbAccess closeDatabase];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
[_objects insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return [self.products count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell.
cell.accessoryType = UITableViewCellAccessoryNone;
Product* product = [self.products objectAtIndex:[indexPath row]];
cell.textLabel.text = product.serial;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return NO;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[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.
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"])
{
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
Product *theProduct = _products[indexPath.row];
[[segue destinationViewController] setDetailItem:theProduct];
NSLog(#"this is prepare for segue");
}
}
- (void)scanditSDKOverlayController: (ScanditSDKOverlayController *)scanditSDKOverlayController
didScanBarcode:(NSDictionary *)barcodeResult
{
// add your own code to handle the barcode result e.g.
scanResult = [barcodeResult valueForKey:#"barcode"];
//barcodelabel.text = [NSString stringWithFormat:#"The barcode is: %#", scanResult];
searchLabel.text = [NSString stringWithFormat:#"%#", scanResult];
[self dismissViewControllerAnimated:YES completion:nil];
self.tableView.contentOffset = CGPointMake(0, 0 - self.tableView.contentInset.top);
[searchLabel becomeFirstResponder];
[super viewDidAppear:YES];
}
- (void)scanditSDKOverlayController: (ScanditSDKOverlayController *)scanditSDKOverlayController
didCancelWithStatus:(NSDictionary *)status
{
// add your own code to handle the user canceling the barcode scan process
}
- (void)scanditSDKOverlayController: (ScanditSDKOverlayController *)scanditSDKOverlayController
didManualSearch:(NSString *)input
{
// add your own code to handle user input in the search bar
// (only required if you use the search bar provided by the Scandit SDK
}
-(IBAction)scanClick:(id)sender;
{
ScanditSDKBarcodePicker *picker = [[ScanditSDKBarcodePicker alloc] initWithAppKey:#"oK1ckH/7EeOPhaseNDXmvNVu+pCX2y6UHZWZ/VYw0hE"];
picker.overlayController.delegate = self;
[picker startScanning];
[self presentViewController:picker animated:YES completion:nil];
//[[self navigationController]pushViewController:picker animated:YES];
[searchLabel becomeFirstResponder];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
searchBar.text = nil;
[searchBar resignFirstResponder];
}
#end

I figured out my own question. for anyone who stumbles across this question, i used NSPredicate. i assumed that if there is a sqlite database then you cannot use NSPredicate, but i made it work. As long as the data is in an array..

Related

How to save and load the added player name

I have searched and searched for how to save and load the added player name to a tableview after apps starts, or leaving the view, but I found out nothing.
Hope someone can help me with this issue.
Below is my code :
#interface PlayersViewController ()
#end
#implementation PlayersViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.players = [NSMutableArray arrayWithCapacity:20];
}
- (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
{
return [self.players count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
PlayerCell *cell = (PlayerCell *)[tableView
dequeueReusableCellWithIdentifier:#"PlayerCell"];
Player *player = [self.players objectAtIndex:indexPath.row];
cell.nameLabel.text = player.name;
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.players removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
[self.tableView reloadData];
}
}
- (void)playerDetailsViewControllerDidCancel:
(PlayerDetailsViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)playerDetailsViewControllerDidSave:
(PlayerDetailsViewController *)controller
{
[self dismissViewControllerAnimated:YES completion:nil];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:#"AddPlayer"])
{
UINavigationController *navigationController =
segue.destinationViewController;
PlayerDetailsViewController
*playerDetailsViewController =
[[navigationController viewControllers]
objectAtIndex:0];
playerDetailsViewController.delegate = self;
}
}
- (void)playerDetailsViewController:
(PlayerDetailsViewController *)controller
didAddPlayer:(Player *)player
{
[self.players addObject:player];
NSIndexPath *indexPath =
[NSIndexPath indexPathForRow:[self.players count] - 1
inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath]
withRowAnimation:UITableViewRowAnimationAutomatic];
[self dismissViewControllerAnimated:YES completion:nil];
}
#interface PlayerDetailsViewController ()
#end
#implementation PlayerDetailsViewController
{
NSString *game;
}
- (IBAction)cancel:(id)sender
{
[self.delegate playerDetailsViewControllerDidCancel:self];
}
- (IBAction)done:(id)sender
{
Player *player = [[Player alloc] init];
player.name = self.nameTextField.text;
[self.delegate playerDetailsViewController:self
didAddPlayer:player];
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (indexPath.section == 0)
[self.nameTextField becomeFirstResponder];
}
- (void)dealloc
{
NSLog(#"dealloc PlayerDetailsViewController");
}
Well, to save your data between application launches, you can rely on this topics: CoreData NSUserDefaults Realm other stuff, like your own server, custom sqlite, etc...
I recommend you start with CoreData guide, that allows you to easy save data between launches.
Hope this may help you.

After adding new cell, how to get the UITableViewControler to save the new entry, so when app is closed and re opened the new cell is there

Ok, so I'm new to iOS Development. I have just created a master view application for note taking. Every thing works fine except for one thing, after a new cell is created and i stop the app and reopen the app the new cell is not there!
Thanks in advance!
Master View Controller.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
#synthesize myTableView, numbers;
- (void)awakeFromNib
{
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
//NSMT arry
numbers = [[NSMutableArray alloc]initWithObjects:#"One",#"Two",#"Three",#"Four", nil];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)viewWillAppear:(BOOL)animated {
}
-(void)viewWillDisappear:(BOOL)animated{
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)insertNewObject:(id)sender
{
UIAlertView * alert = [[UIAlertView alloc] initWithTitle:#"Enter" message:#"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
/*
if (!numbers) {
numbers = [[NSMutableArray alloc] init];
}
[numbers insertObject:[NSDate date] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
*/
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:editing animated:animated];
[myTableView setEditing:editing animated:animated];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return numbers.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [numbers objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[numbers removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[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.
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//if user hits OK
if (buttonIndex == 1) {
NSString * tempTextField = [alertView textFieldAtIndex:0].text;
if (!numbers) {
numbers = [[NSMutableArray alloc] init];
}
[numbers insertObject:tempTextField atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
/*
// 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;
}
*/
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
#end
MasterViewController.h
#import <UIKit/UIKit.h>
#interface MasterViewController : UITableViewController
<UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *myTableView;
#property (strong, nonatomic) NSMutableArray * numbers;
#end
Perhaps tell us how you're storing the data used to populate the tableview. As this is what you need to save.
You could save it using CoreData or just use NSUserDefaults, there are plenty of options open to you. However, without knowing how you data is currently structured it's hard to give you a specific example.
Show some code and you'll get a better answer.

Creating a view controller

I'm creating an iphone app using storyboard. I'm basically new on objective c and Xcode.
I have a list of categories, every time I click on a category it should open a tableView, so I can add an item in that category. But instead of getting a different tableView for each category, its the same table for all the categories and the added items are copied.
How can I create a new table for each label?
Thanks in advance!
Here's what I have for adding a category
#interface ListViewController ()
#end
#implementation ListViewController{
NSMutableArray *items;
}
#synthesize lists;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
items = [NSMutableArray arrayWithCapacity:20];
List *item = [[List alloc] init];
item.title = #"Grocery List";
[items addObject:item];
item = [[List alloc]init];
item.title = #"Project List";
[items addObject:item];
item = [[List alloc] init];
item.title = #"Events List";
[items addObject:item];
self.lists = items;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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.
return [self.lists count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Configure the cell...
/*UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ListsCell"];
List *list = [self.lists objectAtIndex:indexPath.row];
cell.textLabel.text = list.title;*/
ListCell *cell = (ListCell *)[tableView dequeueReusableCellWithIdentifier:#"ListsCell"];
List *list = [self.lists objectAtIndex:indexPath.row];
cell.titleLabel.text = list.title;
return cell;
}
//Add new list, new row will be added on the bottom and its data source must always be sync
-(void)addViewControllerSave:(AddViewController *)controller addList:(List *)list{
[self.lists addObject:list];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.lists count] - 1 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self dismissViewControllerAnimated:YES completion:nil];
}
/*
// 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) {
if(editingStyle == UITableViewCellEditingStyleDelete){
[self.lists removeObjectAtIndex:indexPath.row];
[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 - Navigation
*/
// In a story board-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.
if([segue.identifier isEqualToString:#"AddList"]){
UINavigationController *navigationController = segue.destinationViewController;
AddViewController *addViewController = [[navigationController viewControllers] objectAtIndex:0];
addViewController.delegate = self;
}
else if([segue.identifier isEqualToString:#"ViewItem"]){
UINavigationController *nav = segue.destinationViewController;
ItemViewController *itemViewController = [[nav viewControllers] objectAtIndex:0];
itemViewController.delegate = self;
}
}
#pragma mark - AddViewControllerDelegate
-(void)addViewControllerCancel:(AddViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)addViewControllerSave:(AddViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)itemViewControllerBack:(ItemViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Here's what I have for adding an item:
#interface ItemViewController ()
#end
#implementation ItemViewController{
NSMutableArray *newItems;
}
#synthesize items;
#synthesize delegate;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
newItems = [NSMutableArray arrayWithCapacity:20];
Item *i = [[Item alloc]init];
i.listItem = #"a";
[newItems addObject:i];
self.items = newItems;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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.
return [self.items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Configure the cell...
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ItemsCell"];
Item *item = [self.items objectAtIndex:indexPath.row];
cell.textLabel.text = item.listItem;
return cell;
}
-(void)addIteViewControllerSave:(AddItemViewController *)controller addItem:(Item *)item{
[self.items addObject:item];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.items count] -1 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - Navigation
// In a story board-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.
if([segue.identifier isEqualToString:#"AddItem"]){
UINavigationController *navigationController = segue.destinationViewController;
AddItemViewController *addItemViewController = [[navigationController viewControllers]objectAtIndex:0];
addItemViewController.itemDelegate = self;
}
}
#pragma mark - AddItemViewControllerDelegate
-(void)addItemviewControllerCancel:(AddItemViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
-(void)addIteViewControllerSave:(AddItemViewController *)controller{
[self dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - ItemViewControllerDelegate
-(IBAction)back:(id)sender{
[self.delegate itemViewControllerBack:self];
}
#end
AddItemViewController
#import "AddItemViewController.h"
#import "Item.h"
#interface AddItemViewController ()
#end
#implementation AddItemViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)cancel:(id)sender{
[self.itemDelegate addItemviewControllerCancel:self];
}
-(IBAction)save:(id)sender{
Item *item = [[Item alloc] init];
item.listItem = self.listItemTextField.text;
[self.itemDelegate addIteViewControllerSave:self addItem:item];
}
#end
Don't create a new table view for each label, instead populate it with different data for each label, you will need to change the object you are storing your data in and call
[tableView reloadData];
If all the added items you may need to clear out your array you are using to store the objects before adding the additional content.
[self.items removeAllObjects];

Load DataController before ViewController iOS

I have 2 Controllers, 1 is to load data from JSON, the other is a simple UITableViewController. My problem is that the view is loaded before the data. How can I make the data load before my table? I'm new to Objective-C OOP :/
the code
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "DealsDataController.h"
#import "Deals.h"
#implementation MasterViewController
- (void)awakeFromNib
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
}
[super awakeFromNib];
self.dataController = [[DealsDataController alloc] init];
NSLog(#"this is the awake from nib count %i",[self.dataController countOfList]);
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"did this count the list %i",[self.dataController countOfList]);
return [self.dataController countOfList];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"DealCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
Deals *dealAtIndex = [self.dataController objectInListAtIndex:indexPath.row];
[[cell textLabel] setText:dealAtIndex.name];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return NO;
}
/*
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[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.
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
NSDate *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
*/
#end
and the Data Controller
#import "DealsDataController.h"
#import "Deals.h"
#implementation DealsDataController
#synthesize masterDealsList = _masterDealsList;
-(id)init {
if (self = [super init]) {
[self initializeDataList];
return self;
}
return nil;
}
-(NSMutableArray *)masterDealsList {
if (!_masterDealsList) {
_masterDealsList = [[NSMutableArray alloc] init];
}
return _masterDealsList;
}
-(void)setMasterDealsList:(NSMutableArray *)newList {
if (_masterDealsList != newList) {
_masterDealsList = newList;
}
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
_deals = [json objectForKey:#"deals"]; //2
NSLog(#"deals: %#", _deals);
NSArray *dealName = [_deals valueForKey:#"deal_name"];
NSLog(#"deals Name: %#", dealName);
for (int i = 1;i <= [_deals count]; i++) {
NSDictionary* dict = [_deals objectAtIndex:i-1];
Deals *deal =[[Deals alloc] initWithProdID:1 name:[dict valueForKey:#"deal_name"] description:[dict objectForKey:#"deal_description"] price:10.00 specs:#"specs" terms:#"terms"];
[self addDealWithDeal:deal];
NSLog (#"masterListCount %i ", [self countOfList]);
}
}
-(void)initializeDataList {
//NSDate *today = [NSDate date];
dispatch_async(sweetDealsQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:sweetDealsURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
-(NSUInteger)countOfList {
return [self.masterDealsList count];
}
-(Deals *)objectInListAtIndex:(NSUInteger)theIndex {
return [self.masterDealsList objectAtIndex:theIndex];
}
-(void)addDealWithDeal:(Deals *)deal {
[self.masterDealsList addObject:deal];
}
#end
In MVC, you'd typically have one view controller per view. So a single view controller would be responsible for everything display on one view. Of course, you can have helper classes, or use sub view controllers (e.g. widgets), or if you're developing for iPad, you might have two view controllers (one for the side menu, one for the main view).
I'd suggest you do the following
Make your DataController a subclass of NSObject instead of UIViewController. From what I understand, it is a data access class, not responsible for UI.
In the viewDidLoad method of your MasterViewController, allocate and initialise a DataController object and trigger its data load method.
Either set a callback so when data is fetched, a method on the MasterViewController is called with the data. Or set your MasterViewController as a delegate for your DataController and when it's done, assign the data to a property of the MasterViewController.
i guess you need to perform Data loading before initialising your TableViewController and as you get response Data load the TableViewController. for that refer this post how to wait until some method complete execution, perform data loading in that method.
Its okay to display a blank tableview with an activity indicator overlay while the data is loading. When the data has finished loading, you can just reload the tableview with the data and remove the activity indicator. [tableview reloaddata] would call all of the datasource delegate methods which would then have your data in it.

Crashing On TableView insertRowsAtIndexPath

My app was running fine, I've not modified it to have a dedicated data controller class rather than the data being handled in the main UI class as it was during initial testing. However since the change it keeps crashing when adding a new item to the tableview.
The line of code and error it's crashing on are;
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
2012-07-22 07:17:44.772 speecher[1897:707] * Terminating app due to
uncaught exception 'NSInternalInconsistencyException', reason:
'attempt to insert row 0 into section 0, but there are only 0 rows in
section 0 after the update'
The full code for that class, (the main MasterViewController class) is as follows.
//
// SpeecherMasterViewController.m
// speecher
//
//
#import "SpeecherMasterViewController.h"
#import "SpeecherDataController.h"
#import "SpeecherDetailViewController.h"
#interface SpeecherMasterViewController () {
NSString *newTitle;
NSMutableArray *_speeches;
NSMutableArray *_content;
SpeecherDataController *object;
}
#end
#implementation SpeecherMasterViewController
#synthesize detailViewController = _detailViewController;
- (void)awakeFromNib
{
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
[super awakeFromNib];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
self.detailViewController = (SpeecherDetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
object = [[SpeecherDataController alloc] init];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [object returnNoObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
cell.textLabel.text = [object returnTitle:indexPath.row];
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_speeches removeObjectAtIndex:indexPath.row];
[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;
}
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *titleobj = [object returnTitle:indexPath.row];
NSString *contentobj = [object returnContent:indexPath.row];
self.detailViewController.detailItem = titleobj;
self.detailViewController.detaitContent = contentobj;
}
- (void)insertNewObject:(id)sender
{
//Make sure clear before we start, also make sure initalized (double redundancy with clear statement at end)
newTitle = #"";
//New Title pop up UIAlert View
UIAlertView * alert = [[UIAlertView alloc]
initWithTitle:#"New Speech"
message:#"Please enter a name for speech"
delegate:self
cancelButtonTitle:#"Create"
otherButtonTitles:nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.keyboardType = UIKeyboardTypeDefault;
alertTextField.placeholder = #"Enter a new title";
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
newTitle = [[alertView textFieldAtIndex:0] text];
[object addNewContent:newTitle :#"IT REALLY WORKS!" :#"Nothing"];
//create new speech title, add to array and add to tableview
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
//Clear newTitle for use next time
newTitle = #"";
}
#end
EDIT:
Amended to add [object addNewContent] method & class as per comments,
//
// SpeecherDataController.m
// speecher
//
//
#import "SpeecherDataController.h"
#interface SpeecherDataController ()
{
NSMutableArray *titles;
NSMutableArray *content;
NSMutableArray *timer;
}
#end
#implementation SpeecherDataController
-(void) addNewContent:(NSString*)sTitle : (NSString*)sContent :(NSString*)sTimer
{
[titles insertObject:sTitle atIndex:0];
[content insertObject:sContent atIndex:0];
[timer insertObject:sTimer atIndex:0];
}
//Methods to return data
-(NSString*) returnTitle:(NSUInteger)row
{
return [titles objectAtIndex:row];
}
-(NSString*) returnContent:(NSUInteger)row
{
return [content objectAtIndex:row];
}
-(NSString*) returnTimer:(NSUInteger)row
{
return [timer objectAtIndex:row];
}
-(NSInteger) returnNoObjects
{
return titles.count;
}
#end
The problem is the NSMutableArrays hadn't been alloc and init. Had to add a check to see if they had a init and alloc if not. New check looks like this,
-(void) addNewContent:(NSString*)sTitle : (NSString*)sContent :(NSString*)sTimer
{
if(!titles)
{
titles = [[NSMutableArray alloc] init];
}
if(!content)
{
content = [[NSMutableArray alloc] init];
}
if(!timer)
{
timer = [[NSMutableArray alloc] init];
}
[titles insertObject:sTitle atIndex:0];
[content insertObject:sContent atIndex:0];
[timer insertObject:sTimer atIndex:0];
}

Resources