cellForRowAtIndexPath is not called? - ios

My cellForRowAtIndexPath does not fire everytime
I set dataSource and delegate to the file owner.
I also set referencing outlet.
I also try tbl.delegate=self; and tbl.datasource=self; but it does not work.
What can I do?
-(void)load
{
[name resignFirstResponder];
[salary resignFirstResponder];
name.text=#"";
salary.text=#"";
[tblViewController.data removeAllObjects];
NSString *insertStatement = [NSString stringWithFormat:#"select * from emp"];
sqlite3_stmt *statement;
NSString *path= [self getDBPath];
if (sqlite3_open([path UTF8String], &db) == SQLITE_OK)
{
if (sqlite3_prepare_v2(db, [insertStatement UTF8String], -1,&statement, NULL) == SQLITE_OK)
{
while (sqlite3_step(statement) == SQLITE_ROW)
{
NSMutableDictionary *record=[[NSMutableDictionary alloc]init];
NSString *nm= [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,0)];
NSString * sl= [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,1)];
[record setValue:nm forKey:#"name"];
[record setValue:sl forKey:#"salary"];
NSLog(#"%# %#",nm,sl);
[tblViewController.data addObject:record];
NSLog(#"%#",tblViewController.data);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
NSLog(#"%lu",(unsigned long)[tblViewController.data count]);
[tblViewController.tbl reloadData];
}
//This code is of tableviewcontroller.m
#import "tableViewController.h"
#import "ViewController.h"
#interface tableViewController ()
#end
#implementation tableViewController
#synthesize tbl,data;
#synthesize viewOfTable;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
NSLog(#"only for check");
[self setup];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
//[self setup];
tbl.delegate = self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-( NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-( NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [data count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView
dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[[data objectAtIndex:indexPath.row] valueForKey:#
"name"];
cell.detailTextLabel.text=[[data objectAtIndex:indexPath.row]
valueForKey:#"salary"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//name.text =[[data objectAtIndex:indexPath.row] valueForKey:#"name"];
// salary.text=[[data objectAtIndex:indexPath.row] valueForKey:#"salary"];
}
- (void)setup
{
//Store the whole view in uiView...mac
// [[NSBundle mainBundle] loadNibNamed:#"RegistrationViewController" owner:self options:nil];
viewOfTable=[[UIView alloc]initWithFrame:self.view.frame];
[viewOfTable addSubview:self.view];
self.viewOfTable.translatesAutoresizingMaskIntoConstraints=YES;
}
Please solve my problem.
You didn't get anything then please tell me.

You need to set Table DataSource in order to tableView to construct table rows.
#import "tableViewController.h"
#import "ViewController.h"
#interface tableViewController () <UITableViewDataSource,UITableViewDelegate>
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
tbl.dataSource = self
tbl.delegate = self;
}

Or you can check if you have a fault in your data array, because if its size is 0, there are no rows in a section and no cells within these rows as well and cellForRowAtIndexPath is never called...

You should set dataSource and delegate. When you do this, check tbl. Maybe it nil?
If not check what value returns
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
If you implement
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
check it.
No more options.

Related

How to save the checkmarks in uitableview and show them when the user comes back again to the view?

I am using the following code for showing the checkmarks in the uitableview
{
// NSArray *tableContents;
NSMutableArray *selectedMarks; // You need probably to save the selected cells for use in the future.
}
#property (strong, nonatomic) IBOutlet UITableView *languageTableView;
#property (nonatomic, strong) NSArray *tableContents;
#end
#implementation QPLanguageSettingsController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self initialisation];
selectedMarks = [NSMutableArray new];
}
#pragma mark - View Life Cycle
-(void)initialisation
{
_tableContents = [NSArray arrayWithObjects:#"English",#"Spanish",#"Russian",#"Arabic",#"Portuguese",#"French",#"German",#"German",#"German",#"German",#"German",#"German",#"German",#"German", nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView delegate & datasources
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 14;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"newFriendCell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
//etc.
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.textLabel.textColor = [UIColor whiteColor];
cell.backgroundColor = [UIColor clearColor];
[cell setIndentationLevel:3];
[cell setIndentationWidth:10];
NSString *text = [_tableContents objectAtIndex:[indexPath row]];
//cell.isSelected = [selectedMarks containsObject:text] ? YES : NO;
cell.textLabel.text = text;
NSDictionary *item = [_tableContents objectAtIndex:indexPath.row];
if ([selectedMarks containsObject:item])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
//if you want only one cell to be selected use a local NSIndexPath property instead of array. and use the code below
//self.selectedIndexPath = indexPath;
//the below code will allow multiple selection
NSDictionary *item = [_tableContents objectAtIndex:indexPath.row];
if ([selectedMarks containsObject:item])
{
[selectedMarks removeObject:item];
}
else
{
[selectedMarks addObject:item];
}
[tableView reloadRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
But the problem is that when i come again to the view controller all the checkmarks disappears. how to solve it. Remember i am using multiple selection in uitableview.
I tried the to get solution for your question.I got it successfully.It works perfectly.
This is sample one.Try this code.It works fine.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController<UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UITableView *tableViewCheckMarkPreviousSelectionUpdate;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrProductSelection,*arrProductSelectDeSelectCheckMark;
NSArray *arrayFetchFromDefaults;
}
#end
#implementation ViewController
#synthesize tableViewCheckMarkPreviousSelectionUpdate;
- (void)viewDidLoad
{
[super viewDidLoad];
arrProductSelection = [[NSMutableArray alloc]initWithObjects:#"iPhone",#"iPad",#"iPod",#"iTV",#"iWatch",#"iMac",nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
arrayFetchFromDefaults = [userDefaults objectForKey:#"selectedcheckmark"];
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]initWithArray:arrayFetchFromDefaults];
if(arrProductSelectDeSelectCheckMark.count == 0)
{
arrProductSelectDeSelectCheckMark = [[NSMutableArray alloc]init];
for(int j=0;j<[arrProductSelection count];j++)
{
[arrProductSelectDeSelectCheckMark addObject:#"deselected"];
}
}
[tableViewCheckMarkPreviousSelectionUpdate reloadData];
}
#pragma mark - UITableViewDataSource Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrProductSelection.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:#"deselected"])
cell.accessoryType = UITableViewCellAccessoryNone;
else
cell.accessoryType = UITableViewCellAccessoryCheckmark;
cell.textLabel.text = [arrProductSelection objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - UITableViewDelegate Methods
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
#try
{
CGPoint touchPoint = [cell convertPoint:CGPointZero toView:tableViewCheckMarkSelectionUpdate];
NSIndexPath *indexPath = [tableViewCheckMarkSelectionUpdate indexPathForRowAtPoint:touchPoint];
NSLog(#"%#",arrProductSelectDeSelectCheckMark);
if([arrProductSelectDeSelectCheckMark count]==0)
{
for(int i=0; i<[arrProductSelection count]; i++)
{
[arrProductSelectDeSelectCheckMark addObject:#"deselected"];
}
}
if([[arrProductSelectDeSelectCheckMark objectAtIndex:indexPath.row] isEqualToString:#"deselected"])
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
[arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:#"selected"];
}
else
{
cell.accessoryType = UITableViewCellAccessoryNone;
[arrProductSelectDeSelectCheckMark replaceObjectAtIndex:indexPath.row withObject:#"deselected"];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:arrProductSelectDeSelectCheckMark forKey:#"selectedcheckmark"];
[defaults synchronize];
}
#catch (NSException *exception) {
NSLog(#"The exception is-%#",exception);
}
}
#end
You have multiple solutions:
Using a rational DB on the device like Core-data or SQLite which actually fits your use case but number 3 is more suitable for your use case.
Using NSUserDefaults:
At runtime, you use an NSUserDefaults object to read the defaults that your application uses from a user’s defaults database. NSUserDefaults caches the information to avoid having to open the user’s defaults database each time you need a default
You can find an example here. But NSUserDefaults is to save settings/config/setup information or perhaps user info and NOT for the use case you need.
Using NSCoder which is in my opinion fits your use case.
you can create a Singleton and store data on it :
Singleton.h
#interface Singleton : NSObject
#property (nonatomic, strong) NSArray *rowsChecked;
+ (Singleton *)sharedInstance;
+ (NSArray *)getRowsChecked;
+ (void)setRowsChecked:(NSArray *)rowsChecked;
#end
Singleton.m
#import "Singleton.h"
#implementation Singleton
static Singleton *sharedObject;
+ (Singleton *)sharedInstance;
{
if (sharedObject == nil) {
static dispatch_once_t pred;
dispatch_once(&pred, ^{
sharedObject = [[Singleton alloc] init];
});
}
return sharedObject;
}
+ (NSArray *)getRowsChecked
{
Singleton *singleton = [Singleton sharedInstance];
return singleton.rowsChecked;
}
+ (void)setRowsChecked:(NSArray *)rowsChecked
{
Singleton *singleton = [Singleton sharedInstance];
singleton.rowsChecked= rowsChecked;
}
#end
and to access to your Singleton :
[[Singleton sharedInstance] getRowsChecked]
// or
[[Singleton sharedInstance] setRowsChecked:anArray];
Use the following code:
#import "ViewController.h"
#interface ViewController ()<UITableViewDelegate, UITableViewDataSource>
#property (weak, nonatomic) IBOutlet UITableView *languagesTableView;
#property (strong, nonatomic) NSArray *languagesArray;
#property (strong, nonatomic) NSMutableArray *checkMarksArray;
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.languagesTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
self.languagesArray = [NSArray arrayWithObjects:#"English",#"Spanish",#"Russian",#"Arabic",#"Portuguese",#"French",#"German", nil];
self.checkMarksArray = [[NSMutableArray alloc]init];
if( [[NSUserDefaults standardUserDefaults]objectForKey:#"selectedRowsArray"])
{
self.checkMarksArray = [[[NSUserDefaults standardUserDefaults]objectForKey:#"selectedRowsArray"] mutableCopy];
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.languagesArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *languagesCell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
languagesCell.textLabel.text = self.languagesArray[indexPath.row];
if([self.checkMarksArray containsObject:[NSNumber numberWithLong:indexPath.row]])
{
languagesCell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else
{
languagesCell.accessoryType = UITableViewCellAccessoryNone;
}
[[NSUserDefaults standardUserDefaults]setObject:self.checkMarksArray forKey:#"selectedRowsArray"];
[[NSUserDefaults standardUserDefaults]synchronize];
return languagesCell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
if([self.checkMarksArray containsObject:[NSNumber numberWithLong:indexPath.row]])
{
[self.checkMarksArray removeObject:[NSNumber numberWithLong:indexPath.row]];
}
else
{
[self.checkMarksArray addObject:[NSNumber numberWithLong:indexPath.row]];
}
[self.languagesTableView reloadData];
}
#end
Check this GitHub link:
https://github.com/k-sathireddy/TableViewSelectedCheckMarks

UISearchBar issues Xcode 5

I am having issues with my UISearchBar that I have implemented. My app will compile and run, but as soon as I hit the search bar to begin typing a word in, it crashes. Can anyone tell me if you see anything wrong with my syntax? It is suppose to go through the states that I have in my NSArray.
TableViewController.h:
#import <UIKit/UIKit.h>
#interface TableViewController : UITableViewController <UISearchBarDelegate>
#property (nonatomic, strong) NSMutableArray *results;
#property (nonatomic, strong) IBOutlet UISearchBar *searchBar;
#end
TableViewController.m:
#import "TableViewController.h"
#import "ViewController.h"
#interface TableViewController ()
#end
#implementation TableViewController
{
NSArray *states;
}
- (NSMutableArray *)results
{
if (!_results)
{
_results = [[NSMutableArray alloc] init];
}
return _results;
}
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
states = [NSArray arrayWithObjects:#"Alabama", #"Georgia", #"Tennessee", #"Colorado", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)searchThroughData
{
self.results = nil;
NSPredicate *resultsPredicate = [NSPredicate predicateWithFormat:#"SELF contains [search] $#", self.searchBar.text];
self.results = [[states filteredArrayUsingPredicate:resultsPredicate] mutableCopy];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[self searchThroughData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if(tableView == self.tableView)
{
return [states count];
}
else
{
[self searchThroughData];
return self.results.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
if(tableView == self.tableView)
{
cell.textLabel.text = [states objectAtIndex:indexPath.row];
}
else
{
cell.textLabel.text = self.results[indexPath.row];
}
return cell;
}
I am fairly new to Objective-C, so sorry if this is a simple question that I should know the answer to.
Thanks
The first line of your - (void)searchThroughData method sets the NSMutableArray to nil. This may be the problem.

Fill a tableview with content of array NOT working

Basically what i want to do is i want to fill a table view with strings from an array. I've made a second UIviewcontroller and a custom cell with that show an image and two other labels. But when i run the code, there is no error messages but the tableview is blank, almost like its not recognizing the code at all. I have declared a delegate and datasource for it in the .h file.
#import "ViewController4.h"
#import "Cell.h"
#import "XMLparse.h"
#interface ViewController4 ()
#end
#implementation ViewController4
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(NSMutableArray *)objects {
if (!Datarray) {
Datarray = [[NSMutableArray alloc]init];
}
return Datarray;
}
- (void)viewDidLoad
{
[super viewDidLoad];
Datarray = [[NSMutableArray alloc]initWithObjects:#"USD",#"EUR",#"JPY",#"BGN",#"CZK",#"DKK",#"GBP",#"HUF",#"LTL",#"PLN",#"RON",#"SEK",#"CHF",#"NOK",#"HRK",#"RUB",#"TRY",#"AUD",#"BRL",#"CAD",#"CNY",#"HKD",#"IDR",#"ILS",#"INR",#"KRW",#"MXN",#"MYR",#"NZD",#"PHP",#"SGD",#"THB",#"ZAR", nil];
Tableview.delegate = self;
XMLparse *datee = [[XMLparse alloc]init];
[datee loadDataFromXML];
Date.text = [NSString stringWithFormat:#"Last updated: %#",[datee tid]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)numberOfSectionsInTableview:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableview numberOfRowsInSection:(NSInteger)section {
return [Datarray count];
}
- (CGFloat)tableView:(UITableView *)tableview heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 78;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"Cell";
Cell *cell = (Cell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// cell.ratename.text = [tableData objectAtIndex:indexPath.row];
// cell.thumbnailImageView.image = [UIImage imageNamed:[thumbnails objectAtIndex:indexPath.row]];
cell.currencyname.text = [Datarray objectAtIndex:indexPath.row];
return cell;
}
#end
You have to set self to datasource property of UITableView. I suggest you the following code edited.
- (void)viewDidLoad
{
[super viewDidLoad];
Datarray = [[NSMutableArray alloc]initWithObjects:#"USD",#"EUR",#"JPY",#"BGN",#"CZK",#"DKK",#"GBP",#"HUF",#"LTL",#"PLN",#"RON",#"SEK",#"CHF",#"NOK",#"HRK",#"RUB",#"TRY",#"AUD",#"BRL",#"CAD",#"CNY",#"HKD",#"IDR",#"ILS",#"INR",#"KRW",#"MXN",#"MYR",#"NZD",#"PHP",#"SGD",#"THB",#"ZAR", nil];
Tableview.delegate = self;
Tableview.dataSource = self; // <---- added code for setting datasource.
XMLparse *datee = [[XMLparse alloc]init];
[datee loadDataFromXML];
Date.text = [NSString stringWithFormat:#"Last updated: %#",[datee tid]];
}

UITableView(with sqlite3) not update

i'm korean my english so simple
very very sorry
please help me
my application example phone book.
two View and tab bar with sqlite3 DB
first view is table view cell list, there are name is linked DB
second view save and find and delete phone book list with SQL query.
i want secondview save data and change tab update data list.
i coded [viewDidAppear] reloadData method
close the application re-open apllication is updated.
but not updated change the tap T_T please help me.
FirstViewController.h
#import <UIKit/UIKit.h>
#import "sqlite3.h"
#interface FirstViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>
{
NSString *path;
NSString *dbName;
NSString *databasePath;
sqlite3 *contactDB;
}
#property (nonatomic) sqlite3 *contactDB_2;
#property (strong,nonatomic) IBOutlet UITableView *myTable;
#property (nonatomic,retain) NSMutableArray *quizs;
-(void)checkAndCreateDatabase;
-(void)readFromDatabase;
#end
FistViewController.m
#import "FirstViewController.h"
#import "person.h"
#implementation FirstViewController
#synthesize contactDB_2,myTable;
#synthesize quizs;
-(void)checkAndCreateDatabase{
NSFileManager *filemgr = [NSFileManager defaultManager];
if([filemgr fileExistsAtPath:databasePath] == NO){
const char *dbPath = [databasePath UTF8String];
if(sqlite3_open(dbPath,&contactDB) == SQLITE_OK){
char *errMsg;
const char *sql_stmt = "CREATE TABLE IF NOT EXISTS CONTACTS(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,ADRESS TEXT, PHONE TEXT)";
sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg);
sqlite3_close(contactDB);
}
}
}
-(void)readFromDatabase
{
const char *dbpath = [databasePath UTF8String];
sqlite3_stmt *statement;
if(sqlite3_open(dbpath, &contactDB)==SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat:#"SELECT name,phone FROM contacts"];
const char *query_stmt = [querySQL UTF8String];
if(sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL)==SQLITE_OK)
{
while(sqlite3_step(statement)==SQLITE_ROW){
NSString* nameField = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 0)];
NSString* phoneField = [[NSString alloc]initWithUTF8String:(const char*)sqlite3_column_text(statement, 1)];
person *persons = [person alloc];
[persons setName:nameField];
[persons setPhone:phoneField];
[quizs addObject:persons];
}
sqlite3_finalize(statement);
[myTable reloadData];
}
sqlite3_close(contactDB);
}
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"전화번호목록", #"전화번호목록");
self.tabBarItem.image = [UIImage imageNamed:#"first"];
}
return self;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
pragma mark - View lifecycle
- (void)viewDidLoad
{
dbName = #"contacts2.db";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
databasePath = [documentsDir stringByAppendingPathComponent:dbName];
[self checkAndCreateDatabase];
quizs = [[NSMutableArray alloc] initWithCapacity:100];
[self readFromDatabase];
[super viewDidLoad];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[myTable delegate];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[quizs removeAllObjects];
[self checkAndCreateDatabase];
[self readFromDatabase];
[myTable reloadData];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return quizs.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString* cellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if(cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
}
person *p = [quizs objectAtIndex:indexPath.row];
NSString *str = [[NSString alloc]initWithFormat:#"%# %#",p.name,p.phone];
cell.textLabel.text = str;
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSInteger row = indexPath.row;
NSString *temp = [[NSString alloc]initWithFormat:#"%d번쨰꺼 선택해뜸",row+1];
UIAlertView *alert =[[UIAlertView alloc] initWithTitle:#"터치" message:temp delegate:self cancelButtonTitle:nil otherButtonTitles:#"확인", nil];
[alert show];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
I want change the tab and update cell list.
Actually you can not insert the data in database in background .So until all data are inserted you have to keep application alive. If all data are saved successfully then please write reloadData code in ViewWillAppear.

adding search to NSMutable Array with DetailView

i have project that I'm working on and i need to add search to my uitableview. i have been looking at lots of codes but mostly they are not what i am looking for and i can't modify them . can someone please help me with adding search to my tableview. also i want to push the detailview from searcharray. thank you in advance.
here is the .h uitableview
#import <UIKit/UIKit.h>
#interface Reds : UITableViewController {
NSMutableArray *dummyArray;
}
- (void) setupData;
#end
here is .m uitableview
#import "Reds.h"
#import "RedsDetail.h"
#interface Reds ()
#end
#implementation Reds
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupData];
}
- (void) setupData {
dummyArray = [[NSMutableArray alloc] init];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"dummy 1", #"name" , #"image1.JPG", #"image" , #"dummy 1 description textview", #"description", nil]];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"dummy 2", #"name" , #"image1.JPG", #"image" , #"dummy 2 description textview", #"description", nil]];
[dummyArray addObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:#"dummy 3", #"name" , #"image1.JPG", #"image" , #"dummy 3 description textview", #"description", nil]];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [dummyArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [[dummyArray objectAtIndex:indexPath.row] objectForKey:#"name"];
return cell;
}
#pragma mark - Table view delegate
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"DummyDetail"]){
RedsDetail *dummyDetail = [segue destinationViewController];
NSIndexPath *indexPath = [self.tableView indexPathForCell:sender];
dummyDetail.dummyImageString = [[NSString alloc] initWithString:[[dummyArray objectAtIndex:indexPath.row] objectForKey:#"image"]];
dummyDetail.dummyTextString = [[NSString alloc] initWithString:[[dummyArray objectAtIndex:indexPath.row] objectForKey:#"description"]];
dummyDetail.title = [[NSString alloc] initWithString:[[dummyArray objectAtIndex:indexPath.row] objectForKey:#"name"]];
}
}
#end
here is the .h detailview
#import <UIKit/UIKit.h>
#interface RedsDetail : UIViewController {
IBOutlet UIImageView *dummyImage;
IBOutlet UITextView *dummyText;
NSString *dummyImageString;
NSString *dummyTextString;
}
#property (nonatomic, retain) NSString *dummyImageString;
#property (nonatomic, retain) NSString *dummyTextString;
#end
and finally the .m detailview
#import "RedsDetail.h"
#interface RedsDetail ()
#end
#implementation RedsDetail
#synthesize dummyImageString, dummyTextString;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
dummyImage.image = [UIImage imageNamed:dummyImageString];
dummyText.text = dummyTextString;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#end
i know it might be a easy answer for most of you guys out there but i can't figure it out and i need help. i truly appreciate the time you guys spending in helping me. also i am using xcode 4.5 ios 6 storyboard if that makes a difference in your answers.
adrian
For the search, create a searchArray and a searchText, also you need a textfield that invokes the didChange method.
Use this to link the textfield to the didChange method:
[self.searchTextField addTarget:self action:#selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
Then in the didChange update the searchText and call the updateSearchArray.
-(void)textFieldDidChange:(UITextField*)textField
{
searchTextString = textField.text;
[self updateSearchArray];
}
In the updateSearchArray you compare go through the original array (dummyArray) and if the name is included in the search then add it to the searchArray.
-(void)updateSearchArray
{
if (searchTextString.length != 0) {
searchArray = [NSMutableArray array];
for ( NSDictionary* item in dummyArray ) {
if ([[[item objectForKey:#"name"] lowercaseString] rangeOfString:[searchTextString lowercaseString]].location != NSNotFound) {
[searchArray addObject:item];
}
}
} else {
searchArray = dummyArray;
}
[self.tableView reloadData];
}
Use the searchArray in the tableview methods where you now use the dummyArray.
Updated tableview methods
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [searchArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.textLabel.text = [[searchArray objectAtIndex:indexPath.row] objectForKey:#"name"];
return cell;
}
Also, you need to call a reloadData after adding all the data to the array. And added the updateSearchArray method
- (void)viewDidLoad
{
[super viewDidLoad];
[self setupData];
[self updateSearchArray];
[self.tableView reloadData];
}
To make it easier to implement this I have made a sample project. You can download it here: http://www.rolandkeesom.com/SearchExample.zip

Resources