Reload TaUITableViewbleView - iphone

I have a problem, I make a TabBAr application (with navigationbar), the bar bar is a list of favorits stored in an array.
My problem is that if I change ViewController and add object to array, when I come back to UITableView it isn't reloaded...
This is the class:
-
(void)viewDidLoad {
[super viewDidLoad];
[self readArgFromDatabaseSottoArgomenti];
[self VisualizzaPreferiti];
}
- (void)viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
-(void) readArgFromDatabaseSottoArgomenti {
databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"ARGOMENTI.sqlite"];
sqlite3 *databaseDesc;
// Init the argoments Array
arraySottoArgomenti = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &databaseDesc) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
// const char *sqlStatement = "select * from DESCRIZIONE ";
const char *sqlStatement = [[NSString stringWithFormat:#"SELECT * from DESCRIZIONE ORDER BY id"] UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(databaseDesc, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *aIDArgomento = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescrizione = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aTesto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new argoments object with the data from the database
ContenutoObjectDescrizione *contenutoSottoArgomenti = [[ContenutoObjectDescrizione alloc] initWithName:aID idArgomento:aIDArgomento descrizione:aDescrizione testo:aTesto];
[arraySottoArgomenti addObject:contenutoSottoArgomenti];
[contenutoSottoArgomenti release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(databaseDesc);
}
- (void) VisualizzaPreferiti {
int i;
NSUserDefaults *userPref = [NSUserDefaults standardUserDefaults];
array = [userPref objectForKey:#"array"];
NSLog(#"Retain Count %d Numero ID Array %d",[array retainCount],[array count]);
NSMutableArray *arrayOggettoPreferito;
arrayOggettoPreferito = [[NSMutableArray alloc] init];
ContenutoObjectDescrizione *oggetto = [[ContenutoObjectDescrizione alloc] init];
for (oggetto in arraySottoArgomenti) {
for (i=0; i<[array count]; i++) {
if ([[array objectAtIndex:i] intValue] == [oggetto.id intValue]) {
[arrayOggettoPreferito addObject:oggetto];
NSLog(#"ID %# IDMateria %# Titolo %#",oggetto.id,oggetto.idArgomento,oggetto.descrizione);
}
}
}
listaPref = arrayOggettoPreferito;
arrayOggettoPreferito=nil;
[arrayOggettoPreferito release];
[oggetto release];
}
#pragma mark -
#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 [listaPref count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
cell.textLabel.text = oggettoCercato.descrizione;
NSLog(#"%#",oggettoCercato.descrizione);
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
TestoViewController *testoViewController = [[TestoViewController alloc] initWithNibName:#"TestoView" bundle:nil];
[self.navigationController pushViewController:testoViewController animated:YES];
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
testoViewController.idPreferito = oggettoCercato.id;
testoViewController.title = oggettoCercato.descrizione;
NSString *descrizioneWeb = oggettoCercato.testo;
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[testoViewController.vistaWeb loadHTMLString:descrizioneWeb baseURL:baseURL];
[testoViewController release];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}

Simply calling reloadData doesn't make it do anything unless you update your datasource. In viewWillAppear, you will need to call VisualizzaPreferiti again before you call reloadData.

Related

How to pass value of db to auto complete text filed?

I created auto complete text box my problem is that how to pass array is stored value which is retrive from db
When use _category detail my app will crash .
if i'm using NSArray with objects there is no problem.
When I debug code i found problem in search method plz help to solve my problem
Thank you so much
My function
- (void)viewDidLoad
{
self.categoryDetail = [CompanyDetailDatabase database].categoryDetail;
NSMutableArray *arrt = [[NSMutableArray alloc]init];
//arrt = [NSMutableArray arrayWithArray:_categoryDetail];
arrt=[NSArray arrayWithArray:_categoryDetail];
self.pastUrls = [[NSMutableArray alloc]initWithArray:arrt];
// self.pastUrls = [[NSMutableArray alloc] initWithObjects:#"Hello1",#"Hello2",#"Hello3", nil];
self.autocompleteUrls = [[NSMutableArray alloc] init];
autocompleteTableView = [[UITableView alloc] initWithFrame:CGRectMake(20, 180, 280, 50) style:UITableViewStylePlain];
autocompleteTableView.delegate = self;
autocompleteTableView.dataSource = self;
autocompleteTableView.scrollEnabled = YES;
autocompleteTableView.hidden = YES;
[self.view addSubview:autocompleteTableView];
[txtProduct setDelegate:self];
}
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
// Put anything that starts with this substring into the autocompleteUrls array
// The items in this array is what will show up in the table view
[autocompleteUrls removeAllObjects];
for(NSString *curString in pastUrls)
{
NSRange substringRangeLowerCase = [curString rangeOfString:[substring lowercaseString]];
NSRange substringRangeUpperCase = [curString rangeOfString:[substring uppercaseString]];
if (substringRangeLowerCase.length !=0 || substringRangeUpperCase.length !=0)
{
[autocompleteUrls addObject:curString];
}
}
autocompleteTableView.hidden =NO;
[autocompleteTableView reloadData];
}
#pragma mark UITextFieldDelegate methods
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
autocompleteTableView.hidden = NO;
NSString *substring = [NSString stringWithString:textField.text];
substring = [substring stringByReplacingCharactersInRange:range withString:string];
[self searchAutocompleteEntriesWithSubstring:substring];
return YES;
}
#pragma mark UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger) section {
return autocompleteUrls.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = nil;
static NSString *AutoCompleteRowIdentifier = #"AutoCompleteRowIdentifier";
cell = [tableView dequeueReusableCellWithIdentifier:AutoCompleteRowIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:AutoCompleteRowIdentifier] autorelease];
}
cell.textLabel.text = [autocompleteUrls objectAtIndex:indexPath.row];
return cell;
}
#pragma mark UITableViewDelegate methods
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
txtProduct.text = selectedCell.textLabel.text;
}
Now view of scene image
I'm not sure about your methods. But, it is very simple to achieve. First you've to insert some records in your database table. And, while editing on your UITextField you have to pass the text to your database table as sqlite query with your conditions and returns as NSArray or NSMutableArray Some code snippets -
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if (textField == listTableView)
{
recordsArray = [self getRecords:string];
if ([recordsArray count] == 0 || recordsArray == NULL)
{
[[[UIAlertView alloc] initWithTitle:nil message:#"No Records Were found" delegate:nil cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil] show];
}
else
{
tableV.hidden = NO;
[tableV reloadData];
}
}
return YES;
}
Above will get your typed string and pass to database method named as getRecords with typed string.
-(NSMutableArray*)getRecords:(NSString *)srchString
{
NSMutableArray *mutArray = [[NSMutableArray alloc]init];
sqlite3 *servicesDB;
NSString *filePath=[AppDelegate dbPath];
if(sqlite3_open([filePath UTF8String], &servicesDB) == SQLITE_OK)
{
NSString *sqlStatement;
sqlStatement = [NSString stringWithFormat:#"SELECT * FROM Records WHERE record = '%%%#%%'", srchString];
const char *sql = [sqlStatement UTF8String];
sqlite3_stmt *select_statement;
if (sqlite3_prepare_v2(servicesDB, sql, -1, &select_statement, nil) == SQLITE_OK)
{
while (sqlite3_step(select_statement) == SQLITE_ROW)
{
char *record = (char *)sqlite3_column_text(select_statement, 0);
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:[NSString stringWithUTF8String:record] forKey:#"record"];
[mutArray addObject:[dict copy]];
}
}
else
{
NSLog(#"Error while fetching data. '%s'", sqlite3_errmsg(servicesDB));
}
sqlite3_finalize(select_statement);
}
sqlite3_close(servicesDB);
return mutArray;
}
Above database method will execute and fetch the data which are all having word whatever you're typed. You can find the details about LIKE clause here
You'll get your final result once the executions are completed. Simply find a sample project here

Not calling Method didSelectRowAtIndexPath:

didSelectRowAtIndexPath: method is not calling even after connecting table delegate and DataSource to file owner.
when i am trying to print something it is not printing in this methods
find my code below for your reference:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [favorite count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell= nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"mycell"];
if (cell == nil) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"mycell"];}
db * temp =(db *)[self.favorite objectAtIndex:indexPath.row];
cell.textLabel.text=temp.name;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
NSLog(#"b");
UITableViewCell *selectedCell = [secondTable cellForRowAtIndexPath:indexPath];
[secondTable.delegate tableView:secondTable didSelectRowAtIndexPath:indexPath];
cellText = selectedCell.textLabel.text;
NSLog(#"%#",cellText);
[fav addObject:cellText];
arrayTwo = tableTw.tableTwo;
msg = [NSString stringWithFormat: #" %# ",[arrayTwo objectAtIndex:0]];
NSLog(#"%#",[arrayTwo objectAtIndex:0]);
}
-(void)checkAndCreateDatabase{
BOOL success;
NSFileManager *fileManager=[NSFileManager defaultManager];
success=[fileManager fileExistsAtPath:databasePath];
if(success)
return;
NSString *databasePathFromApp = [[[NSBundle mainBundle]resourcePath] stringByAppendingPathComponent:databaseName];
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
}
-(IBAction)resPage:(id)sender{
NSLog(#"%#",fav);
sqlite3 *database;
favorite=[[NSMutableArray alloc]init];
if(sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK){
NSString *sql=[NSString stringWithFormat:#"SELECT name,item_country.id,text.text FROM country,item_country,text WHERE country.name ='%#' AND text.item = item_country.item AND country.id = item_country.id", cellText];
const char *sqlStatement = [sql UTF8String];;
sqlite3_stmt *compiledStatement;
NSLog(#"a");
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL)==SQLITE_OK){
NSLog(#"A");
while (sqlite3_step(compiledStatement)==SQLITE_ROW) {
d=[NSString stringWithCString:(char *)sqlite3_column_text(compiledStatement, 2) encoding:NSUTF8StringEncoding];
a= [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
db *info =[[db alloc]initWithText:(NSString *)d andAg:(NSString *)a];
[favorite addObject:info];
}
}
sqlite3_finalize(compiledStatement);
sqlite3_close(database);
if(favorite.count >0){
txt.text = [NSString stringWithFormat:#"%# ", [favorite objectAtIndex:0] ];
}}
}
- (void)viewDidLoad {
{
databaseName=#"nobel10.db";
NSArray *documentPaths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentDir = [documentPaths objectAtIndex:0];
databasePath=[documentDir stringByAppendingPathComponent:databaseName];
[self checkAndCreateDatabase];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
[super viewDidLoad];
if (tableOn == nil) {
tableOn = [[table1 alloc] init];
}
if (tableTw == nil) {
tableTw = [[table2 alloc] init];
}
if (tableThre == nil) {
tableThre = [[table3 alloc] init];
}
if (tableFou == nil) {
tableFou = [[table4 alloc] init];
}
[firstTable setDataSource:tableOn];
[secondTable setDataSource:tableTw];
[thirdTable setDataSource:tableThre];
[fourthTable setDataSource:tableFou];
[fifthTable setDataSource:tableFiv];
[firstTable setDelegate:tableOn];
[secondTable setDelegate:tableTw];
[thirdTable setDelegate:tableThre];
[fourthTable setDelegate:tableFou];
tableOn.view = tableOn.tableView;
tableTw.view = tableTw.tableView;
tableThre.view = tableThre.tableView;
tableFou.view = tableFou.tableView;
{fav=[[NSMutableArray alloc]init];
cellText =[[NSString alloc]init];
secondTable=[[UITableView alloc]init];
secondTable.delegate=self;
secondTable.dataSource=self;
secondTable.tag = 20;
[self.view addSubview:secondTable];
}
}
suggestions please !
I think secondTable isn't the object you work on.Make sure it.
Add in .h file and at the dalegate calling time call dataSource.
obj_TableView.delegate = self;
obj_TableView.dataSource = self;
Then try it.

search bar not working?

i have a SQL file where 5 different type of data is stored. I am adding this data in a dictionary specified with keys. and then i am adding this dictionary to tableData array as a dataSource for table and searchBar. But it is not searching anything.
adding code below
- (void)viewDidLoad {
[super viewDidLoad];
dataSource =[[NSMutableArray alloc] init];
tableData = [[NSMutableArray alloc]init];
searchedData = [[NSMutableArray alloc]init];
NSString *query = [NSString stringWithFormat:#"SELECT * FROM Vegetables"];
SQLite *sqlObj1 = [[SQLite alloc] initWithSQLFile:#"ShoppersWorld.sqlite"];
[sqlObj1 openDb];
[sqlObj1 readDb:query];
// [query release];
for (int i=0; i<[dataSource count]; i++) {
NSLog(#"data:%#",[dataSource objectAtIndex:i]);
}
while ([sqlObj1 hasNextRow])
{
NSString *name=[sqlObj1 getColumn:1 type:#"text"];
NSString *price=[sqlObj1 getColumn:2 type:#"text"];
NSString *quantity=[sqlObj1 getColumn:3 type:#"text"];
NSString *unit=[sqlObj1 getColumn:4 type:#"text"];
NSString *total=[sqlObj1 getColumn:5 type:#"text"];
dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys: name,#"nameOfVegetables",
price,#"priceOfVegetables",
quantity,#"quantityOfVegetables",
unit,#"unitOfVegetables",
total,#"totalPriceOfVegetables",nil];
//NSLog(#"results:%# %#",dict);
[dataSource addObject:dict];
}
[tableData addObjectsFromArray:dataSource];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
// Configure the cell.
else {
cell.productLbl.text= [NSString stringWithFormat:#"%#",[[tableData objectAtIndex:indexPath.row]objectForKey:#"nameOfVegetables"] ];
cell.bPriceLbl.text = [NSString stringWithFormat:#"Rs %d/Kg",
[[[tableData objectAtIndex:indexPath.row] objectForKey:#"priceOfVegetables"] intValue]];
cell.qtyLbl.text = [NSString stringWithFormat:#"QTY: %# %#",[[tableData objectAtIndex:indexPath.row]
objectForKey:#"quantityOfVegetables"],[[tableData objectAtIndex:indexPath.row] objectForKey:#"unitOfVegetables"]] ;
cell.tPriceLbl.text = [NSString stringWithFormat:#"TOTAL: %#",[[tableData objectAtIndex:indexPath.row]
objectForKey:#"totalPriceOfVegetables"]];
}
return cell;
}
#pragma search operations
- (IBAction)search:(id)sender{
sBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0,40,320,30)];
sBar.delegate = self;
[self.view addSubview:sBar];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
// only show the status bar’s cancel button while in edit mode
[sBar setShowsCancelButton:YES animated:YES];
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tableData removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
[sBar setShowsCancelButton:NO animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[tableData removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] || searchText==nil){
[tableview reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in dataSource)
for (int i = 0; i < [dataSource count]; i++)
{
NSMutableDictionary *temp = (NSMutableDictionary*) [dataSource objectAtIndex:i];
NSString *name = [NSString stringWithFormat:#"%#", [temp valueForKey:#"nameOfVegetables"]];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[tableData addObject:name];
}
}
counter++;
[pool release];
}
[tableview reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
sBar.hidden= YES;
// if a valid search was entered but the user wanted to cancel, bring back the main list content
[tableData removeAllObjects];
[tableData addObjectsFromArray:dataSource];
#try{
[tableview reloadData];
}
#catch(NSException *e){
}
[sBar resignFirstResponder];
sBar.text = #"";
}
In search delegate methods you manipulate not with searchedData but tableData array. As these name suggest, array searchedData is supposed to store filtered data.
By the way, your approach to use sqlite for data source and absorbing all database into array is wrong. In cellForRowAtIndexPath read from sqlite database only data you need at the moment.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// load from sqlite only data for this cell.
// Use searchBar.text with sqlite's LIKE to filter data from database
NSUInteger row = [indexPath row];
static NSString *CellIdentifier = #"SignsCellIdentifier";
UITableViewCell *cell = [table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSString *sql = [NSString stringWithFormat:#"SELECT fieldNameFromTable FROM TableName WHERE FieldToLookForIn LIKE \"%%%#%%\" LIMIT 1 OFFSET %u", searchBar.text ? searchBar.text : #"", row];
sqlite3_stmt *stmt;
int res = sqlite3_prepare_v2(database, [sql UTF8String], -1, &stmt, NULL);
if (res != SQLITE_OK) {
NSLog(#"sqlite3_prepare_v2() failed"];
return nil;
}
if (sqlite3_step(stmt) == SQLITE_ROW) {
const unsigned char *name = sqlite3_column_text(stmt, 0);
cell.text = [NSString stringWithUTF8String:(const char*)name];
}
sqlite3_finalize(stmt);
return cell;
}
How to apply search in this approach? In textDidChange do nothing but call [tableView reloadData]. And in cellForRowAtIndexPath load data with sqlite LIKE using searchBar.text as search term. So reloadData will load only filtered records. searchBarSearchButtonClicked will call only resignFirstResponder of it's caller, removing keyboard off screen. It doesn't need to do anything more because search is already done. searchBarCancelButtonClicked will set text property of it's caller to nil, call reload data and again call resignFirstResponder.
- (void)searchBarCancelButtonClicked:(UISearchBar *)s {
s.text = nil;
[tableView reloadData];
[s resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)s {
// search is already done
[s resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[tableView reloadData];
}
numberOfRowsInSection should also request db with the same SELECT as in cellForRowAtIndexPath, but with SELECT COUNT. Writing this method will be your homework)

viewWillAppear is never called [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
iphone viewWillAppear not firing
I have a problem, I have a tabBar / NavigationBar application. I try to use viewWillAppear but nothing. If I put a simple NSLog the console not show. Where is the problem?
-(void)viewDidLoad {
[super viewDidLoad];
[self readArgFromDatabaseSottoArgomenti];
[self VisualizzaPreferiti];
}
- (void)viewWillAppear:(BOOL)animated {
NSLog(#"test");
[self VisualizzaPreferiti];
[self.tableView reloadData];
}
-(void) readArgFromDatabaseSottoArgomenti {
databasePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"ARGOMENTI.sqlite"];
sqlite3 *databaseDesc;
// Init the argoments Array
arraySottoArgomenti = [[NSMutableArray alloc] init];
// Open the database from the users filessytem
if(sqlite3_open([databasePath UTF8String], &databaseDesc) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
// const char *sqlStatement = "select * from DESCRIZIONE ";
const char *sqlStatement = [[NSString stringWithFormat:#"SELECT * from DESCRIZIONE ORDER BY id"] UTF8String];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(databaseDesc, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *aID = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *aIDArgomento = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *aDescrizione = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *aTesto = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
// Create a new argoments object with the data from the database
ContenutoObjectDescrizione *contenutoSottoArgomenti = [[ContenutoObjectDescrizione alloc] initWithName:aID idArgomento:aIDArgomento descrizione:aDescrizione testo:aTesto];
[arraySottoArgomenti addObject:contenutoSottoArgomenti];
[contenutoSottoArgomenti release];
}
}
// Release the compiled statement from memory
sqlite3_finalize(compiledStatement);
}
sqlite3_close(databaseDesc);
}
- (void) VisualizzaPreferiti {
int i;
NSUserDefaults *userPref = [NSUserDefaults standardUserDefaults];
array = [userPref objectForKey:#"array"];
NSLog(#"Retain Count %d Numero ID Array %d",[array retainCount],[array count]);
NSMutableArray *arrayOggettoPreferito;
arrayOggettoPreferito = [[NSMutableArray alloc] init];
ContenutoObjectDescrizione *oggetto = [[ContenutoObjectDescrizione alloc] init];
for (oggetto in arraySottoArgomenti) {
for (i=0; i<[array count]; i++) {
if ([[array objectAtIndex:i] intValue] == [oggetto.id intValue]) {
[arrayOggettoPreferito addObject:oggetto];
NSLog(#"ID %# IDMateria %# Titolo %#",oggetto.id,oggetto.idArgomento,oggetto.descrizione);
}
}
}
listaPref = arrayOggettoPreferito;
arrayOggettoPreferito=nil;
[arrayOggettoPreferito release];
[oggetto release];
}
#pragma mark -
#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 [listaPref count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
cell.textLabel.text = oggettoCercato.descrizione;
NSLog(#"%#",oggettoCercato.descrizione);
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:indexPath animated:YES];
TestoViewController *testoViewController = [[TestoViewController alloc] initWithNibName:#"TestoView" bundle:nil];
[self.navigationController pushViewController:testoViewController animated:YES];
ContenutoObjectDescrizione *oggettoCercato = [[ContenutoObjectDescrizione alloc] init];
oggettoCercato = [listaPref objectAtIndex:[indexPath row]];
testoViewController.idPreferito = oggettoCercato.id;
testoViewController.title = oggettoCercato.descrizione;
NSString *descrizioneWeb = oggettoCercato.testo;
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[testoViewController.vistaWeb loadHTMLString:descrizioneWeb baseURL:baseURL];
[testoViewController release];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[sup
er dealloc];
}
Add [super viewWillAppear]; and give it a try.

Selected row in UITableView shows a different result in the next TabBarViewController

I have been trying to figure out what went wrong with this segment in my code. It was working fine for a normal UITableView, which has data extracted from a local database (results after clicking a button).
However, after I used this similar code for a UITableView that shows results of a search (I was trying to do a multiple category search but failed), there has been errors, differences between the selected row and the outcome or results on the TabBarViewController.
Following is my code for the linkage to the TabBarViewController.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
TabBarViewController *tabBarView = [[TabBarViewController alloc] initWithNibName:#"TabBarViewController" bundle:[NSBundle mainBundle]];
Attraction *att = [attractions objectAtIndex: indexPath.row];
tabBarView.attraction = att;
[self.navigationController presentModalViewController:tabBarView animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tabBarView release];
}
Here are my full codes for you to inspect:
-(void) checkAndCreateDatabase{
// Check if the SQL database has already been saved to the users phone, if not then copy it over
databaseName = #"funsg.sql";
// Get the path to the documents directory and append the databaseName
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:databaseName];
//NSLog([NSString stringWithFormat:#"GetData %#", databasePath]);
BOOL success;
// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];
// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
[fileManager release];
}
-(void)createEditableCopyOfDatabaseIfNeeded {
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:#"abc.sql"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success) return;
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:#"abc.sql"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
NSAssert1(0, #"Failed to create writable database file with message '%#'.", [error localizedDescription]);
}
}
-(void) readAttractionsFromDatabase {
[self checkAndCreateDatabase];
// Open the database
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
// Setup the SQL Statement and compile it for faster access
const char *sqlStatement = [[NSString stringWithFormat:#"select * from everything "] UTF8String];
//NSLog([NSString stringWithFormat:#"select * from everything"]);
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
// Read the data from the result row
NSString *bus = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *desc = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *location = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *mrt = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *image = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *type = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *carpark = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
// Create a new animal object with the data from the database
Attraction *att = [[Attraction alloc] initWithName:desc buses:bus add:location type:type mrt:mrt image:image name:name carpark:carpark];
if (attractions == NULL)
// There should not be a NULL name
NSLog(#"Null name!!");
else {
[attractions addObject:att];
// Apparently the addObject function in NSMutableArray does not
// keep a copy of our object, so, we can't release it.
//[name release];
[att release];
}
}
sqlite3_finalize(compiledStatement); // Cleanup the statement
}
else {
NSLog(#"Error retrieving data from database.");
}
sqlite3_close(database);
}
else {
NSLog(#"Error: Can't open database!");
}
}
-(void)viewDidLoad {
[super viewDidLoad];
attractions = [[NSMutableArray alloc] init];
searchedNames = [[NSMutableArray alloc] init];
[self loadData];
}
-(void) insertToDB :(Attraction*) att {
[self checkAndCreateDatabase];
if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
static sqlite3_stmt *compiledStatement;
sqlite3_exec(database, [[NSString stringWithFormat:#"INSERT INTO everything (Bus,Description,Location,MRT,Name,image,type,Carpark) SELECT '%#','%#','%#','%#', '%#', '%#', '%#', '%#' WHERE NOT EXISTS (SELECT 1 FROM everything WHERE Name = '%#');", att.buses,att.desc,att.add, att.mrt, att.name, att.image, att.type , att.carpark,att.name] UTF8String], NULL, NULL, NULL);
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
-(void) loadData {
//First fetch the data from the JSON
NSURL *url = nil;
NSString *querystring = [NSString stringWithFormat:#"http://mp15.bitproj1.com/testsearch.php"];
url = [NSURL URLWithString:querystring];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
//NSLog(#"jsonreturn"); // Look at the console and you can see what the restults are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
self.data = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (data==nil){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Internet Connection" message:#"Unable to update the data." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
self.rows =[data objectForKey:#"attractions"];
for (int i=0; i<[self.rows count]; i++) {
NSDictionary *dict = [rows objectAtIndex: i];
Attraction* a = [[Attraction alloc] initWithName:[dict objectForKey:#"Description"]
buses:[dict objectForKey:#"Bus"]
add:[dict objectForKey:#"Location"]
type:[dict objectForKey:#"type"]
mrt:[dict objectForKey:#"MRT"]
image:[dict objectForKey:#"image"]
name:[dict objectForKey:#"Name"]
carpark:[dict objectForKey:#"Carpark"]];
//Here we insert the data, when inserting we check for the duplicates. If the record already exists we do not insert. Code also must be optimized later
[self insertToDB:a];
}
}
[jsonreturn release];
[self readAttractionsFromDatabase];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return(1);
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return([searchedNames 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] autorelease];
}
NSString *cellText = [searchedNames objectAtIndex:indexPath.row];
[cell.textLabel setText:cellText];
return cell;
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
}
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[searchedNames removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""] || searchText==nil) {
// Nothing to search, empty result.
[myTableView reloadData];
return;
}
for (NSString *att in attractions) {
Attraction* p = ((Attraction *)att);
NSRange r = [p.name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(r.location != NSNotFound) {
[searchedNames addObject:p.name];
}
}
[myTableView reloadData];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
TabBarViewController *tabBarView = [[TabBarViewController alloc] initWithNibName:#"TabBarViewController" bundle:[NSBundle mainBundle]];
Attraction *att = [attractions objectAtIndex: indexPath.row];
tabBarView.attraction = att;
[self.navigationController presentModalViewController:tabBarView animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
[tabBarView release];
}
-(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
-(void)viewDidUnload {
}
-(void)dealloc {
[data release];
[attractions release];
[super dealloc];
}
#end
Are you using two different array as datasource? If so, I think you are not retrieving the value from the correct array.
And also I can't understand the use of this code:
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
You can change that code as:
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
Edit
You are using two diff arrays searchedNames, attractions. There is the problem:
if(searching==YES)
{
//retrieve the values from searchedNames array
}
else
{
//retrieve the values from attractions array
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
searching=YES;
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
searching=NO;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if(searching==YES)
return([searchedNames count]);
else
return [attractions 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] autorelease];
}
NSString *cellText;
if(searching==YES)
cellText = [searchedNames objectAtIndex:indexPath.row];
else
cellText = [attractions objectAtIndex:indexPath.row];
[cell.textLabel setText:cellText];
return cell;
}