Need help on update and delete sqlite on the tableview - xcode

I'm a beginner on xcode and I have very little knowledge about it. Here is my code. I'm doing a simple account management program for iOS 6.0. I need to select the row from where i'm going to edit/delete my data from the table view and then be able to update/delete it. I don't know how to code those and I need help from experienced programmers.
My project: http://www.mediafire.com/?95l8pwzu3c62ts0
#import "FlipsideViewController.h"
#interface FlipsideViewController ()
#end
#implementation FlipsideViewController
#synthesize entries;
- (void)viewDidLoad
{
self.label.text=self.strUsername;
entries = [[NSMutableArray alloc]init];
[self openDB];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM SUMMARY8 WHERE theuser = '%s'",[self.label.text UTF8String]];
sqlite3_stmt *statement;
if (sqlite3_prepare(account, [sql UTF8String], -1, &statement, nil)==SQLITE_OK)
{
while (sqlite3_step(statement)==SQLITE_ROW){
char *field1=(char *) sqlite3_column_text(statement, 0 );
NSString *field1Str = [[NSString alloc]initWithUTF8String:field1];
char *field2=(char *) sqlite3_column_text(statement, 1 );
NSString *field2Str = [[NSString alloc]initWithUTF8String:field2];
char *field3=(char *) sqlite3_column_text(statement, 2 );
NSString *field3Str = [[NSString alloc]initWithUTF8String:field3];
char *field4=(char *) sqlite3_column_text(statement, 3 );
NSString *field4Str = [[NSString alloc]initWithUTF8String:field4];
NSString *str = [[NSString alloc]initWithFormat:#"%# - %# - %#", field1Str,field3Str,field4Str];
[entries addObject:str];
}
}
[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.
}
-(NSString *) filePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
return [[paths objectAtIndex:0]stringByAppendingPathComponent:#"account.sql"];
}
-(void) openDB
{
if (sqlite3_open([[self filePath] UTF8String], &account) !=SQLITE_OK){
sqlite3_close(account);
NSAssert(0,#"Database failed to open");
}
else
{
NSLog(#"database opened");
}
}
- (IBAction)addaccount:(id)sender {
MainViewController *FVC = [self.storyboard instantiateViewControllerWithIdentifier:#"MainViewController"];
FVC.strUsername=self.strUsername;
[self presentViewController:FVC animated:YES completion:nil];
// FVC.label.text=self.label.text;
}
- (IBAction)btnEdit:(id)sender {
}
- (IBAction)btnDelete:(id)sender {
[self tableView:<#(UITableView *)#> cellForRowAtIndexPath:<#(NSIndexPath *)#>];
}
#pragma mark - Actions
- (IBAction)done:(id)sender
{
[self.delegate flipsideViewControllerDidFinish:self];
}
-(NSInteger) numberOfSectionsInTableView: (UITableView *)tableView
{
return 1;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
NSString *myTitle = [[NSString alloc]initWithFormat:#"Name - Username - Password"];
return myTitle;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d", [entries count]);
return [entries count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{//NSLog(#"test");
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [self.entries objectAtIndex:indexPath.row];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSString *selectedRow = [entries objectAtIndex:indexPath.row];
NSString *sql = [NSString stringWithFormat:#"DELETE FROM SUMMARY8 WHERE name = '%#'",selectedRow];
char *err;
if (sqlite3_exec(account, [sql UTF8String], NULL, NULL, &err)!=SQLITE_OK){
sqlite3_close(account);
NSAssert(0, #"Could not delete row");
}
else {
NSLog(#"row deleted");
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Done" message:#"Account was deleted successfully!" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
#end
is this correct? sorry I absolutely have no background on Xcode. So sorry for the bother..

Delete use this:
Example:strUpdate = [NSString stringWithFormat:#"DELETE FROM SUMMARY8 WHERE theuser = '%s'",[self.label.text UTF8String]];
Update use this:
Example(updating the status):strQuery = [NSString stringWithFormat:#"UPDATE SUMMARY8 SET STATUS='1' WHERE theuser = '%s'",[self.label.text UTF8String]];
Hope this helps.
EDIT:
use this method:
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
Example: NSString *selectedRow = [entries objectAtIndex:indexPath.row];
}
This method basically shows the data for that row of table. manipulate with that data. Given examples.. Tweak it according to your situation...
EDIT 2:
For example:
UITableView *table = [[UITableView alloc] init];
[self tableView:table didSelectRowAtIndexPath:index];
where index is your item number.

Related

Xcode - Segue issues

i've been trying to get a segue to work. I've written the following... but for some reason, the ...preparesegue... method doesnt fire. I've read other related posts but i cant get it to fire, and just as importantly, the variable i'm need isnt transferred.
m file:
#implementation CountryTableViewController
-(void) getData:(NSData *) data {
NSError *error;
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
[self.tableView reloadData];
}
-(void) start {
NSURL *url = [NSURL URLWithString: URL];
NSData *data = [NSData dataWithContentsOfURL:url];
[self getData:data];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self start];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [json count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellId = #"CellIdentifier";
TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
if (!cell) {
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
}
NSDictionary *info = [json objectAtIndex:indexPath.row];
cell.TitleLabel.text = [info objectForKey:#"CountryName"];
cell.ReferenceLabel.text = [info objectForKey:#"id"];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender tableView:(UITableView *)tableView {
//if ([segue.identifier isEqualToString:#"CountryToState"]) {
NSLog(#"TEST");
NSIndexPath *path = [self.tableView indexPathForSelectedRow];
TableViewCell *cell = (TableViewCell *)[tableView cellForRowAtIndexPath:path];
NSString *countryRef = [[cell ReferenceLabel] text];
TableViewControllerStates *TVCS = [segue destinationViewController];
TVCS.receivedReferenceNumber = countryRef;
//}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//TableViewCell *cell = (TableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
//NSString *countryRefNumber = [[cell ReferenceLabel] text];
[self performSegueWithIdentifier:#"CountryToState" sender:tableView];
}
h file
#import <UIKit/UIKit.h>
#define URL #"http://localhost/Rs.php"
#interface CountryTableViewController : UITableViewController <UITableViewDelegate, UITableViewDataSource> {
NSMutableArray *json;
}
Any help appreciated; thank you in advance.

close uitableview and reload another uitableview

i have problem.
I have CityViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"MainStoryboard" bundle:nil];
TheatreController *tmpTheatreController = [storyboard instantiateViewControllerWithIdentifier:#"TheatreController"];
NSString *cityView = [[self.arrayCity objectAtIndex:indexPath.row] valueForKey:#"idCity"];
tmpTheatreController.cityView = cityView;
//[self.navigationController pushViewController:tmpTheatreController animated:YES];
[tmpTheatreController.tableView reloadData];
[self.delegate citiesViewControllerCancel:self];
}
When i select the city pass correctly the "idCity" in TheatreController.m
...
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([segue.identifier isEqualToString:#"SelectCity"])
{
UINavigationController *nc = segue.destinationViewController;
CityViewController *mvc = [[nc viewControllers] objectAtIndex:0];
mvc.delegate = self;
}
}
...
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *webUrl = #"http://localhost:3000/theatres?city=";
webUrl = [webUrl stringByAppendingFormat:#"%#", cityView];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:webUrl]];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES]; });
}
- (void)fetchedData:(NSData *)responseData {
NSArray* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions error:nil];
NSMutableArray *theatreTMP = [[NSMutableArray alloc] initWithCapacity:[json count]];
int i = 0;
for (id object in [json valueForKeyPath:#"response.name"]) {
Theatres *t = [[Theatres alloc] init];
NSLog(#"JSON: %#", [[json valueForKeyPath:#"response.name"] objectAtIndex:i]);
t.theatre = [[json valueForKeyPath:#"response.name"] objectAtIndex:i];
t.idTheatre = [[json valueForKeyPath:#"response.id"] objectAtIndex:i];
[theatreTMP addObject:t];
i++;
}
self.arrayTheatre = [theatreTMP copy];
[self.tableView reloadData];
}
I have correctly the response of the server and all parameter are correct, but the problem i have with reloadData of the tableView main![enter image description here][1]. I dont see the update table.
HELP ME thanks
i have resolved with this solution
In the CityViewController.m
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cityView = [[self.arrayCity objectAtIndex:indexPath.row] valueForKey:#"idCity"];
[self.delegate performSelector:#selector(reloadTable:) withObject:cityView];
[self.delegate citiesViewControllerCancel:self];
}
and in the TheatreTableView.m
- (void) callServer:(NSString *)idCity {
NSString *webUrl = #"http://localhost:3000/theatres?city=";
webUrl = [webUrl stringByAppendingFormat:#"%#", idCity];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:webUrl]];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];});
}
....
- (void) reloadTable:(id)idCity
{
[self callServer:idCity];
}
Thanks

TableViewController Vs UIViewController and a tableView inside

I have a Master/Details Application.By default, we have the MasterViewController attached to a TableViewController, in addition, i have attached it to an Sqlite database and all the data are showing correctly as they should. So i added a UISearchBar, in order to search upon all the items ; Search functionality's were working fine but the only bug was, the search bar disappears when scrolling down. So as a solution, i removed the TableViewController and created a simple UIVIewController and added a TableView , TableViewCell and a search bar in order to keep the search bar fix on top of the View as suggested by many people.Now the difference between those two concepts is, the TableViewController (First Case) loads the whole data in the cells once the application loads, when the ViewController ( Second Case , with a tableView , tableViewCell and a searchBar) does not load anything at startup, It loads the different elements when the user start writing a word in the searchBar. How can i force the tableView to load all Elements at startup, just like if you have a TableViewCOntroller?
This is my code :
//
// MasterViewController.m
#import "MasterViewController.h"
#import "DetailViewController.h"
#import <sqlite3.h>
#import "Author.h"
#interface MasterViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation MasterViewController
NSString *authorNAme , *authorNAme2;
#synthesize tableView;
#synthesize searchWasActive;
#synthesize detailViewController = _detailViewController;
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext = __managedObjectContext;
#synthesize theauthors;
NSString *PathDB;
-(BOOL)canBecomeFirstResponder{
return YES;
}
- (void)awakeFromNib
{
// self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
[super awakeFromNib];
}
- (void)viewDidLoad
{
// [self numberOfSectionsInTableView:tableView];
//[self tableView:tableView willDisplayCell:[self.tableView dequeueReusableCellWithIdentifier:#"Cell"] forRowAtIndexPath:0];
//[self.tableView
searchBar.delegate = (id)self;
// [self.tableView reloadData];
// [self configureCell:#"Cell" atIndexPath:0];
[self authorList];
[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 = (DetailViewController *)[[self.splitViewController.viewControllers lastObject] topViewController];
}
- (void)viewDidUnload
{
[self setTableView:nil];
tableView = nil;
searchBar = nil;
[self setSearchWasActive:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
- (void)insertNewObject:(id)sender
{
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSEntityDescription *entity = [[self.fetchedResultsController fetchRequest] entity];
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:[entity name] inManagedObjectContext:context];
// If appropriate, configure the new managed object.
// Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template.
[newManagedObject setValue:[NSDate date] forKey:#"timeStamp"];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
//[self authorList];
// [filteredTableData release];
//[self.tableView reloadData];
NSLog(#"Cancel Button Clicked");
// Scroll to top
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
self.searchDisplayController.searchBar.text =#" ";
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)sender
{
[self.tableView reloadData];
searchBar.showsCancelButton=NO;
}
-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text
{
searchBar.showsCancelButton=NO;
if(text.length == 0)
{
isFiltered = FALSE;
}
else
{
isFiltered = true;
filteredTableData = [[NSMutableArray alloc] init];
for (Author* author in theauthors)
{ //[NSPredicate predicateWithFormat:#"SELECT * from books where title LIKE %#", searchBar.text];
NSRange nameRange = [author.name rangeOfString:text options:NSAnchoredSearch];
NSRange descriptionRange = [author.genre rangeOfString:text options:NSAnchoredSearch];
if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound)
{
[filteredTableData addObject:author];
NSLog(#"Item Added is %#" , author.name);
}
}
}
[self.tableView reloadData];
}
#pragma mark - Table View methods
-(NSMutableArray *) authorList{
[self numberOfSectionsInTableView:tableView];
theauthors = [[NSMutableArray alloc] initWithCapacity:1000000];
// NSMutableArray * new2 = [[NSMutableArray alloc ] initWithCapacity:100000];
// authorNAme = theauthors.sortedArrayHint.description;
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSLog(#"Before the dbpath variable");
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"dictionary_native.sqlite"];
NSLog(#"After the dbpath variable");
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"1");
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
NSLog(#"Database correctly located");
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"2");
NSLog(#"An error has occured: %#", sqlite3_errmsg(db));
}
NSLog(#"Database correctly opened");
// const char *sql = "SELECT F_Keyword FROM wordss";
const char *sql = "SELECT * FROM wordss";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
// NSLog(#"entered the while statement");
Author * author = [[Author alloc] init];
// // NSLog(#"Author initialised");
//
author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
// NSLog(#"this is the author.name %#" , author.name);
author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 2)];
//
// authorNAme=author.genre;
//
[theauthors addObject:author];
}
// authorNAme = author.genre;
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %#", sqlite3_errmsg(db));
}
#finally {
// sqlite3_finalize(sqlStatement);.
// authorNAme = nil;
// authorNAme = Nil;
return theauthors;
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// return [[self.fetchedResultsController sections] count];
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
// return [sectionInfo numberOfObjects];
int rowCount;
if(self->isFiltered)
rowCount = filteredTableData.count;
else
rowCount = theauthors.count;
NSLog(#"This is the number of rows accepted %i" , rowCount);
return rowCount;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:#"Cell"];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
int rowCount = indexPath.row;
Author *author = [self.theauthors objectAtIndex:rowCount];
if(isFiltered){
author = [filteredTableData objectAtIndex:indexPath.row];
}
else{
author = [theauthors objectAtIndex:indexPath.row];
}
cell.textLabel.text = author.name;
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) {
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error = nil;
if (![context save:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// The table view should not be re-orderable.
return NO;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath];
// self.detailViewController.detailItem = object;
// DetailViewController* vc ;
MasterViewController *author;
NSLog(#"This is the showDetailsForIndexPath");
[self->searchBar resignFirstResponder];
// Details* vc = [self.storyboard instantiateViewControllerWithIdentifier:#"Details"];
// AuthorVC* author;
if(isFiltered)
{
author = [filteredTableData objectAtIndex:indexPath.row];
}
else
{
author = [theauthors objectAtIndex:indexPath.row];
}
//vc.author = author;
authorNAme = author.genre;
authorNAme2 = author.name ;
// author = [theauthors objectAtIndex:indexPath.row];
NSLog(#"This is the author.genre %#" , author.genre);
//vc.author.genre = author.genre;
authorNAme = author.genre;
authorNAme2 = author.name;
//NSLog(#"This is the details %#",vc.author.genre);
NSLog(#"This is the authorNAme Variable %#" , authorNAme);
self.detailViewController.detailItem = authorNAme;
self.detailViewController.detailItem2 = authorNAme2;
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (__fetchedResultsController != nil) {
return __fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Event" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return __fetchedResultsController;
}
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
// UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[self.tableView endUpdates];
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
// NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
// cell.textLabel.text = [[object valueForKey:#"timeStamp"] description];
}
#end
Any help Will be highly appreciated...Thank you for taking the time.
If the tableview is in xib link it to correct object and set delegate and datasource.

CustomCell in XCode not displaying value

I created a custom cell in table view that has a search bar. Text entered by users will be used to search a SQLite db and results displayed in table view. The problem I have now is that the search result is not displayed in the table view if I use custom cell but works when I use the default cell. For e.g., in code below, if I use [cell setText:currentSubLocality]; it will display the result but it will not display result if I use cell.lblG.text = currentLocation;. Please help, been struggling with it for 2 days. Thanks
#import "CustomViewController.h"
#import "FMDBDataAccess.h"
#import "locationCode.h"
#import "CustomCell.h"
#interface CustomViewController ()
#end
#implementation CustomViewController{
NSMutableArray *searchResults;}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [searchResults count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"vvv"];
if (cell==nil){
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"vvv"];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
locationCode *code = [[locationCode alloc] init];
code= [searchResults objectAtIndex:indexPath.row];
NSString *currentLocation = code.location;
NSString *currentSubLocality = code.subLocality
//[cell setText:currentSubLocality];
cell.lblG.text = currentLocation;
cell.lblL.text = currentSubLocality;
}
return cell;
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSString *databasePath = [[NSBundle mainBundle] pathForResource:#"spr" ofType:#"sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:databasePath];
[database open];
searchResults = [[NSMutableArray alloc] initWithObjects:nil count:0];
NSString *query = [NSString stringWithFormat:#"select * from Locations where locationCode like '%#%%'", searchText];
FMResultSet *results = [database executeQuery:query];
while([results next]) {
locationCode *code = [[locationCode alloc] init];
code.code = [results stringForColumn:#"locationcode"];
code.subLocality= [results stringForColumn:#"sublocality"];
code.longitude= [results stringForColumn:#"longitude"];
code.latitude= [results stringForColumn:#"latitude"];
[searchResults addObject:code];
}
[database close];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller
shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#end
Try This it will work. paste the below code in cellforrowatindexpath method and don't forget to set your TableViewCell "Identifier" in your Attribute inspector
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
I solved the problem by adding the tableview as an outlet. Then change the following line
CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:#"vvv"];
to
CustomCell *cell = [customTableView dequeueReusableCellWithIdentifier:#"vvv"];

XCode error EXC_BAD_ACCESS when using sqlite3 + table + tab bar

I have a class ClsDatabase that is called to save / retrieve data.
There are also 2 views. The 2nd view have table that will display information based on what ClsDataBase retrieved. A tab-bar controls the 2 views.
It can load initially with the 1st view shown. However, when I select the 2nd view, it stops at main.m's
return UIApplicationMain(argc, argv, nil, NSStringFromClass([TestTabBarAppDelegate class]));
with error message: EXC_BAD_ACCESS.
I tried create another project but without ClsDatabase and just print some dummmy values in table, and it works. Not sure if its because of the class ClsDatabase
AppDelegate.m
#import "TestTabBarAppDelegate.h"
#import "TestTabBarFirstViewController.h"
#import "TestTabBarSecondViewController.h"
#implementation TestTabBarAppDelegate
#synthesize window = _window;
#synthesize tabBarController = _tabBarController;
- (void)dealloc
{
[_window release];
[_tabBarController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
UIViewController *viewController1 = [[[TestTabBarFirstViewController alloc] initWithNibName:#"TestTabBarFirstViewController" bundle:nil] autorelease];
UIViewController *viewController2 = [[[TestTabBarSecondViewController alloc] initWithNibName:#"TestTabBarSecondViewController" bundle:nil] autorelease];
self.tabBarController = [[[UITabBarController alloc] init] autorelease];
self.tabBarController.viewControllers = [NSArray arrayWithObjects:viewController1, viewController2, nil];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
(2nd view).h
#import <UIKit/UIKit.h>
#import "ClsDatabase.h"
#interface TestTabBarSecondViewController : UIViewController<UIApplicationDelegate, UITabBarControllerDelegate>{
NSArray *arrDebtor;
ClsDatabase *dbDebtor;
}
#end
(2nd view.m)
#import "TestTabBarSecondViewController.h"
#implementation TestTabBarSecondViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Second", #"Second");
self.tabBarItem.image = [UIImage imageNamed:#"second"];
}
return self;
}
- (void)viewDidLoad
{
NSString *strSql;
dbDebtor = [[ClsDatabase alloc] initWithDbName:#"Debt"];
arrDebtor = [[NSArray alloc] init];
strSql = [NSString stringWithFormat:#"SELECT * FROM Debtor"];
arrDebtor = [dbDebtor ReturnQueryArray:strSql];
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if ([arrDebtor count] == 0) {
return 1;
}
else {
return [arrDebtor count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Debtor";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if ([arrDebtor count] == 0) {
if (indexPath.row == 1) {
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
cell.textLabel.text = [NSString stringWithFormat:#"No tables or records found"];
return cell;
}
}
else {
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
}
NSMutableDictionary *dictDebtor = [arrDebtor objectAtIndex:indexPath.row];
cell.textLabel.text = [dictDebtor valueForKey:#"Name"];
return cell;
}
}
You are doing lot's of things in code that should be done with IB and storyboarding.
Your logic in cellForRowAtIndexPath will fail on the first row, when indexPath.row is 0 and your arrDebtor is empty and your cell has not been created yet. That would explain the EXC_BAD_ACCESS error.

Resources