NSPredicate Ignore Numbers In String [pinyin] - ios

I've looked around a lot but have been unable to find an answer for this one...
I have a class in my app that contains Chinese Pinyin pronunciation set up as
pronunciation# [space] pronunciation#
for instance 你好[hello] would be
ni3 hao3
so my question is how can I get NSPredicate to ignore the numbers in the string/class during a search?
ideally I would be able to search:
"nihao"
"ni hao"
etc
and still end up with the same result (你好 ni3 hao3)
I've tried out a few LIKE instances but have failed miserably every time...
Thanks
here's my array, as per request:
-(NSMutableArray *) wordList{
cdh = [[NSMutableArray alloc] initWithCapacity:10];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"cdh.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %s", sqlite3_errmsg(db));
}
const char *sql = "SELECT * FROM MAIN";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
Words * word = [[Words alloc] init];
word.head = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,0)];
word.pro = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
word.def = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
[cdh addObject:word];
}
}
sqlite3_finalize(sqlStatement);
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return cdh;
}
}
Words.h
#import <Foundation/Foundation.h>
#import "TestViewController.h"
#interface Words : NSObject {
NSString *head;
NSString *pro;
NSString *def;
}
#property(nonatomic, copy) NSString *head;
#property(nonatomic, copy) NSString *pro;
#property(nonatomic, copy) NSString *def;
#end
Words.m
#import "Words.h"
#implementation Words
#synthesize head;
#synthesize pro;
#synthesize def;
- (NSString *)searchableStringValue {
NSCharacterSet *invalidSet = [[NSCharacterSet characterSetWithCharactersInString:#"[]0123456789 "] invertedSet];
NSString *searchString = [[pro componentsSeparatedByCharactersInSet:invalidSet] componentsJoinedByString:#""];
return searchString;
}
#end
TestViewController.h
#import <UIKit/UIKit.h>
#import <sqlite3.h>
#import "Words.h"
#interface TestViewController : UITableViewController {
NSMutableArray *cdh;
sqlite3 * db;
}
#property(nonatomic,retain) NSMutableArray *cdh;
#property (nonatomic, strong) NSData *myData;
-(NSMutableArray *) wordList;
#end
TestViewController.m (inc. predicate)
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"(head beginswith[c] %#) OR (searchableStringValue beginswith[c] %#)", searchText, searchText];
searchResults = [cdh filteredArrayUsingPredicate:resultPredicate];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//#warning Incomplete method implementation.
// Return the number of rows in the section.
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return [self.cdh count];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
//UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
// int rowCount = indexPath.row;
// Words *word = [self.cdh objectAtIndex:rowCount];
// cell.textLabel.text = word.head;
// cell.detailTextLabel.text = [NSString stringWithFormat:#"%# %#", word.pro, word.def];
// Configure the cell...
Words *word = nil;
if (tableView == self.searchDisplayController.searchResultsTableView) {
word = [searchResults objectAtIndex:indexPath.row];
} else {
word = [cdh objectAtIndex:indexPath.row];
}
cell.textLabel.text = word.head;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# %#", word.pro, word.def];
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:#"ShowWordDetails"]) {
NSIndexPath *indexPath = nil;
Words *word = nil;
if (self.searchDisplayController.active) {
indexPath = [self.searchDisplayController.searchResultsTableView indexPathForSelectedRow];
word = [searchResults objectAtIndex:indexPath.row];
} else {
indexPath = [self.tableView indexPathForSelectedRow];
word = [cdh objectAtIndex:indexPath.row];
}
DetailsViewController *destViewController = segue.destinationViewController;
destViewController.word = word;
}
}

Your strings are contained in a Words class. This gives you a perfect opportunity to create additional methods to help out with processing the strings it holds (i.e. you don't need to try doing everything in the predicate).
For instance, consider adding a method which returns:
- (NSString *)searchableStringValue
this method would take the string that you are currently trying to search and mutate it to remove the brackets, numbers, spaces. This can most easily be achieved with:
NSCharacterSet *invalidSet = [[NSCharacterSet characterSetWithCharactersInString:#"[]0123456789 "] invertedSet];
NSString *searchString = [[##XXX## componentsSeparatedByCharactersInSet:invalidSet] componentsJoinedByString:#""];
where ##XXX## is the string that you are currently trying to search.
Now, your predicate should use searchableStringValue, instead of the string that you are currently trying to search.

Related

How to Impliment Search bar in Table view for Contacts in ios [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
i have following code in viewdidload
totalstring=[[NSMutableArray alloc]initWithObjects:#"a",#"b",#"c",#"d",#"e",#"f",#"g",#"h",#"i",#"j",#"k",#"l",#"m",#"n",#"n",#"o",#"p",#"q",#"r",#"s",#"s",#"t",#"u",#"v",#"w",#"x",#"y",#"z", nil];
indid=indidvalue1;
NSLog(#"the ind id value is %#",indid);
serviceCall=[[Services alloc]init];
NSString *contactsDisplay1=#"ContactDetails";
NSDictionary *contactsDisplayDetails1 =#{#"IND_ID":indid};
[serviceCall ContactsDisplayUrl:contactsDisplay1 ContactsDisplayDetails:contactsDisplayDetails1];
[serviceCall setDelegate:self];
code for implimenting search bar
{
filteredstring =[[NSMutableArray alloc]init];
for (NSString *str in totalstring )
{
NSRange stringrange =[str rangeOfString:searchText options:NSCaseInsensitiveSearch];
if(stringrange.location!= NSNotFound)
{
[filteredstring addObject:str];
}
}
}
[tableView reloadData];
code for table view
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:simpleTableIdentifier];
}
if (tableView == self.searchDisplayController.searchResultsTableView)
{
cell.textLabel.text = [searchResultsArray objectAtIndex:indexPath.row];
} else
{
UIFont *myfont=[UIFont fontWithName:#"Arial" size:35];
cell.textLabel.text = [contactNameSplitDisplayArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[relationTypeSplitDisplayArray objectAtIndex:indexPath.row];
cell.textLabel.font=myfont;
}
return cell;
How can i implement search bar in table view for contacts in story board ?I am new to iOS
?
and how to implement plus button and dots button within the table view?
Devi my complete answer.It works perfectly.I use search bar.Also use that delegate methods.
ViewController.h
#import <UIKit/UIKit.h>
#import <Contacts/Contacts.h> //Must import contact framework
#interface ViewController : UIViewController<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
#property (strong, nonatomic) IBOutlet UISearchBar *searchbarContacts;
#property (strong, nonatomic) IBOutlet UITableView *tableViewContactData;
#end
ViewController.m
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *arrayTableData;
NSMutableArray *arraySearchContactData;
}
#end
#implementation ViewController
#synthesize tableViewContactData;
#synthesize searchbarContacts;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
arrayTableData = [[NSMutableArray alloc]init];
arraySearchContactData = [[NSMutableArray alloc]init];
[self fetchContactsandAuthorization];
[tableViewContactData registerClass:[UITableViewCell class] forCellReuseIdentifier:#"cell"];
[self.view addSubview:tableViewContactData];
}
//Fetching Contact and Authorization access
-(void)fetchContactsandAuthorization
{
// Request authorization to Contacts
CNContactStore *store = [[CNContactStore alloc] init];
[store requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (granted == YES) {
//keys with fetching properties
NSArray *keys = #[CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactImageDataKey];
NSString *containerId = store.defaultContainerIdentifier;
NSPredicate *predicate = [CNContact predicateForContactsInContainerWithIdentifier:containerId];
NSError *error;
NSArray *cnContacts = [store unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
if (error) {
NSLog(#"error fetching contacts %#", error);
} else {
NSString *phone;
NSString *fullName;
NSString *firstName;
NSString *lastName;
UIImage *profileImage;
NSMutableArray *contactNumbersArray = [[NSMutableArray alloc]init];
for (CNContact *contact in cnContacts)
{
// copy data to my custom Contacts class.
firstName = contact.givenName;
lastName = contact.familyName;
if (lastName == nil) {
fullName=[NSString stringWithFormat:#"%#",firstName];
}else if (firstName == nil){
fullName=[NSString stringWithFormat:#"%#",lastName];
}
else{
fullName=[NSString stringWithFormat:#"%# %#",firstName,lastName];
}
UIImage *image = [UIImage imageWithData:contact.imageData];
if (image != nil) {
profileImage = image;
}else{
profileImage = [UIImage imageNamed:#"person-icon.png"];
}
for (CNLabeledValue *label in contact.phoneNumbers)
{
phone = [label.value stringValue];
if ([phone length] > 0) {
[contactNumbersArray addObject:phone];
}
}
NSDictionary* personDict = [[NSDictionary alloc] initWithObjectsAndKeys: fullName,#"fullName",profileImage,#"userImage",phone,#"PhoneNumbers", nil];
[arrayTableData addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
[arraySearchContactData addObject:[NSString stringWithFormat:#"%#",[personDict objectForKey:#"fullName"]]];
NSLog(#"The contactsArray are - %#",arrayTableData);
}
dispatch_async(dispatch_get_main_queue(), ^{
[tableViewContactData reloadData];
});
}
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - UITableView Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrayTableData.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *strCell = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:strCell];
if(cell==nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCell];
}
cell.textLabel.text = arrayTableData[indexPath.row];
return cell;
}
#pragma mark - SearchBar Delegate Methods
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
#try
{
[arrayTableData removeAllObjects];
stringSearch = #"YES";
NSString *name = #"";
if ([searchText length] > 0)
{
for (int i = 0; i < [arraySearchContactData count] ; i++)
{
name = [arraySearchContactData objectAtIndex:i];
if (name.length >= searchText.length)
{
NSRange titleResultsRange = [name rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
{
[arrayTableData addObject:[arraySearchContactData objectAtIndex:i]];
}
}
}
}
else
{
[arrayTableData addObjectsFromArray:arraySearchContactData];
}
[tableViewContactData reloadData];
}
#catch (NSException *exception) {
}
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)SearchBar
{
SearchBar.showsCancelButton=YES;
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)theSearchBar
{
[theSearchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)SearchBar
{
#try
{
SearchBar.showsCancelButton=NO;
[SearchBar resignFirstResponder];
[tableViewContactData reloadData];
}
#catch (NSException *exception) {
}
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)SearchBar
{
[SearchBar resignFirstResponder];
}
#end
The Printed results For Contacts
The contactsArray are - (
"John Appleseed",
"Kate Bell",
"Anna Haro",
"Daniel Higgins",
"David Taylor",
"Hank Zakroff"
)
Please Refer the below link, i can able to implement the search bar in table view by using this.
http://www.appcoda.com/search-bar-tutorial-ios7/

Passing data from sqlitedatabase to a Detailview

I'm creating an iOS app which is a directory system, where on the first page I load data such as a list of some states in a tableview (from a sqlite database). When clicking on a state only the districts under that particular state have to be displayed in the detailview's tableview. My problem is that when clicking on each district the phonenumber of that district must be shown in the next view controller. Can somebody please help?
This is the firstview.
#implementation firstview
#synthesize ddetails=_ddetails;
#synthesize at,arraydata,show,table;
static firstview *_database;
+ (firstview*)database {
if (_database == nil) {
_database = [[firstview alloc] init];
}
return _database;}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [theauthors count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30;}
- (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];
}
menu *me = [self.theauthors objectAtIndex:indexPath.row];
cell.textLabel.text=me.state;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
[_button setTitle:cellText forState:UIControlStateNormal];
menu *infos=[theauthors objectAtIndex:indexPath.row];
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"detailViewController"] ;
_ddetails.uniqueId=infos.id;
// NSLog(#"%#",infos.state);
// NSLog(#"%d",infos.id);
[self.navigationController pushViewController:_ddetails animated:NO];
}
-(NSMutableArray *) authorList{
theauthors = [[NSMutableArray alloc]init] ;
show=[[NSMutableArray alloc]init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"menu.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %s", sqlite3_errmsg(db));
}
NSString *query =[NSString stringWithFormat:#"SELECT id,category FROM category "];
sqlite3_stmt *selectstmt;
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &selectstmt, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(selectstmt)==SQLITE_ROW) {
menu * men = [[menu alloc] init];
men.id= sqlite3_column_int(selectstmt,0);
men.state=[NSString stringWithUTF8String:(char *) sqlite3_column_text(selectstmt,1)];
[theauthors addObject:men];
// NSLog(#"%#",men.category);
// NSLog(#"%d",men.id);
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return theauthors;
}
}
- (detailsnews *)Detailsnews:(int)uniqueId{
NSLog(#"%d",uniqueId);
detailsnews *get=nil;
_the=[[NSMutableArray alloc]init];
_gets=[[NSMutableArray alloc]init];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"menu.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %s", sqlite3_errmsg(db));
}
NSString *sqls =[NSString stringWithFormat:#"SELECT * FROM menulist where category=%d",uniqueId];
// NSLog(#"%d",uniqueId);
sqlite3_stmt *selectstmt6;
if(sqlite3_prepare(db, [sqls UTF8String], -1, &selectstmt6, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(selectstmt6)==SQLITE_ROW) {
// NSLog(#"%d",uniqueid);
int totalValue = 0;
int uniqueId = sqlite3_column_int(selectstmt6,0);
// NSLog(#"%d",uniqueid);
[_gets addObject:[NSNumber numberWithInt:uniqueId]];
for(NSNumber *number in _gets) // Use fast enumeration to iterate through the array
{
totalValue = [number intValue];
// NSLog(#"%d",totalValue);
}
char *nameChars = (char *) sqlite3_column_text(selectstmt6, 2);
NSString *name = [[NSString alloc] initWithUTF8String:nameChars];
char *rec = (char *) sqlite3_column_text(selectstmt6, 1);
NSString *rece = [[NSString alloc] initWithUTF8String:rec];
// NSLog(#"%#",rece);
[_the addObject:rece];
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in _the)
{
[result appendString:[obj description]];
result = [_the componentsJoinedByString: #"\r"];
// NSLog(#"%#",result);
}
//[_the addObject:[NSNumber numberWithInt:uniqueid]];
// int totalValue = 0;
// for(NSNumber *number in _the) // Use fast enumeration to iterate through the array
// {
// totalValue = [number intValue];
// NSLog(#"%d",totalValue);
// }
//
// NSMutableString * result = [[NSMutableString alloc] init];
// int totalValue = 0;
//for (NSObject * obj in _the)
// {
// [result appendString:[obj description]];
// result = [_the componentsJoinedByString: #"\r"];
// NSLog(#"%#",result);
// }
//NSArray *arr=[result componentsSeparatedByString:#"\r"];
// NSMutableString * vgh = [[NSMutableString alloc] init];
// for (NSObject * obj in arr)
// {
//[vgh appendString:[obj description]];
// vgh = [arr componentsJoinedByString: #"\r"];
// }
get = [[detailsnews alloc] initWithUniqueId:totalValue district:result phonenumber:name ];
//NSLog(#"%#",_the);
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return get;
}
}
detailview controller
- (void)viewDidLoad
{
[super viewDidLoad];
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
if (details != nil) {
NSArray *arrComponents = [details.district componentsSeparatedByString:#"\r"];
arr = [[NSMutableArray alloc] init];
for(int i = 0; i < [arrComponents count] ;i++)
{
NSString *str = [arrComponents objectAtIndex:i];
[arr addObject:str];
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arr count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 30;}
- (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];
}
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
cell.textLabel.text=[arr objectAtIndex:indexPath.row];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *selectedCell = [tableView cellForRowAtIndexPath:indexPath];
NSString *cellText = selectedCell.textLabel.text;
[button2 setTitle:cellText forState:UIControlStateNormal];
detailsnews *details = [[firstview database]
Detailsnews:_uniqueId];
//NSLog(#"%d",details.uniqueId);
// NSLog(#"%#",details.rece);
// detailsnews *infos=[arr objectAtIndex:indexPath.row];
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"phonelistViewController"] ;
_ddetails.uniqueId=details.uniqueId;
// NSLog(#"%d",details.uniqueId);
[self.navigationController pushViewController:_ddetails animated:NO];
}
You need to Pass the data including the phoneNumbers from first stateViewController to District and then from District to DetailsPage…I would suggest pass an NSdictionary which Includes the data from one view to another such as..In second ViewController declare a global Dictionary as mainDictionary..
and in didSelectRowAtIndexPath just pass the data as
self.ddetails = [self.storyboard instantiateViewControllerWithIdentifier:#"phonelistViewController"] ;
_ddetails.mainDict=AllThe Details;
Do the same thing with PhoneNumbers also

Exception in UISearchBar

I'm trying to implement the searchBar following steps in this Video
But I got the following exception when I press the searchBar
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Can't do regex matching on object <Authors: 0x10960c1e0>.'
AuthorsTableViewController.h
#interface AuthorsTableViewController : UITableViewController <UISearchBarDelegate> {
NSMutableArray *authorsArray;
NSMutableArray *resultArray;
QuotesNavController *quotes;
}
#property (nonatomic, strong) IBOutlet UISearchBar *SearchBar;
#property (nonatomic, retain) NSMutableArray *authorsArray;
#property (nonatomic, retain) NSMutableArray *resultArray;
-(sqlite3 *) openDataBase;
-(IBAction)backToQuotes:(id)sender;
#end
AuthorsTableViewController.m
#import "AuthorsTableViewController.h"
#interface AuthorsTableViewController ()
#end
#implementation AuthorsTableViewController
#synthesize authorsArray, resultArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
[self retrieveDataFromSqlite];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)backToQuotes:(id)sender{
[self performSegueWithIdentifier:#"backToQuotes" sender:sender];
}
-(sqlite3 *) openDataBase{
sqlite3 *database;
NSString *sqLiteDb = [[NSBundle mainBundle] pathForResource:#"SuccessQuotes" ofType:#"sqlite"];
if (sqlite3_open([sqLiteDb UTF8String], &database) != SQLITE_OK) {
NSLog(#"Failed to open database!");
}else{
NSLog(#"database opened!");
}
return database;
}
-(void) retrieveDataFromSqlite{
authorsArray = [[NSMutableArray alloc] init];
sqlite3 *myDatabase = [self openDataBase];
const char *sqlSelect = "SELECT *, COUNT(qu_author) AS count FROM authors JOIN quotes ON _auid = qu_author GROUP BY au_name ORDER BY au_name ASC";
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(myDatabase, sqlSelect, -1, &compiledStatement, NULL) == SQLITE_OK) {
while(sqlite3_step(compiledStatement) == SQLITE_ROW) {
int author_id = sqlite3_column_int(compiledStatement, 0);
NSString *au_name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 1)];
NSString *au_picture = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 2)];
int quotes_id = sqlite3_column_int(compiledStatement, 3);
NSString *quotes_content = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 4)];
int quotes_author = sqlite3_column_int(compiledStatement, 5);
NSString *quotes_favorite = [NSString stringWithUTF8String:(char *) sqlite3_column_text(compiledStatement, 6)];
int count = sqlite3_column_int(compiledStatement, 7);
Authors *authors = [[Authors alloc] initWithUniqueId:author_id au_name:au_name au_picture:au_picture quotes_id:quotes_id quotes_content:quotes_content quotes_author:quotes_author quotes_author:quotes_author quotes_favorite:quotes_favorite count:count];
[authorsArray addObject:authors];
} // while end
}// prepare end
sqlite3_finalize(compiledStatement);
sqlite3_close(myDatabase);
}
- (void) searchThroughtData {
self.resultArray = nil;
NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"SELF like[c] %#",[NSString stringWithFormat:#"%#*",self.SearchBar.text]];
self.resultArray = [[self.authorsArray filteredArrayUsingPredicate:resultPredicate] mutableCopy];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.tableView) {
return [authorsArray count];
} else {
[self searchThroughtData];
return [resultArray count];
}
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
[self searchThroughtData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"authorCell";
AuthorsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell = [[AuthorsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
Authors *temp_items;
if (tableView == self.tableView) {
temp_items = [self.authorsArray objectAtIndex:indexPath.row];
}else{
temp_items = [self.resultArray objectAtIndex:indexPath.row];
}
[cell.authorName setText:[NSString stringWithFormat:#"%#",temp_items.au_name]];
[cell.count setTitle:[NSString stringWithFormat:#"%d",temp_items.count] forState:UIControlStateNormal];
UIImage *theImage = [UIImage imageNamed:temp_items.au_picture];
cell.authorPic.image = theImage;
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:93/255.0
green:45/255.0
blue:22/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Authors *temp_items = [self.authorsArray objectAtIndex:indexPath.row];
quotes = [self.storyboard instantiateViewControllerWithIdentifier:#"QuotesNavController"];
quotes.quType = 3;
quotes.authorId = temp_items.author_id;
[self presentModalViewController:quotes animated:YES];
}
#end

NSMutable array is empty by the time Table View tries to read it

right now I'm getting and error regarding a table view cell trying to read data from an object. I am hitting a database, storing all the rows into an NSMUtable Array as object which seems to be working fine. But when I want the table view to read that array, I keep getting 'null'. Any help would be greatly appreciated.
ERROR
-[AttendeeData isEqualToString:]: unrecognized selector sent to instance 0x751ca80
2013-03-16 11:40:52.499 ExpoRequestLite[39716:c07] * Terminating app due to uncaught exception 'NSInvalidArgumentException',
#interface DashLandingViewController ()
#end
#implementation DashLandingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self){
// Custom initialization
}
return self;
}
- (void)viewDidLoad {
[super viewDidLoad];
entries = [[NSMutableArray alloc]init];
_attendeeDataToPush = [[AttendeeData alloc]init];
[self openDB];
NSString *sql = [NSString stringWithFormat:#"SELECT * FROM data"];
sqlite3_stmt *statement;
if(sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil)== SQLITE_OK) {
while(sqlite3_step(statement) == SQLITE_ROW){
NSLog(#"got all attendees");
NSString *firstName = [[NSString alloc] initWithUTF8String:(const char *)sqlite3_column_text(statement, 2)];
_attendeeDataToPush.firstNameValue = firstName;
[entries addObject:_attendeeDataToPush];
NSLog(#"array has %#", [[entries objectAtIndex:0] firstNameValue]);
}
}
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [entries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
NSLog(#"selected firstname is %#", [[entries objectAtIndex:0] firstNameValue]);
cell.textLabel.text = [entries objectAtIndex:indexPath.row];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
#end
Error suggests that you have error somewhere else in your code, post your complete code. From your error it seems that you are calling isEqualToString: on object which is not string type. Your code does not show where you getting the error. For Using isEqualToString: both objects should be of NSString type. If you are comparing object with string then use isEqual: instead.
Errors may happening here
NSLog(#"selected firstname is %#", [[entries objectAtIndex:0] firstNameValue]);
cell.textLabel.text = [entries objectAtIndex:indexPath.row];
Modify these lines to,
if([entries count] > indexPath.row){
AttendeeData *attendeeData = [entries objectAtIndex:indexPath.row];
NSLog(#"selected firstname is %#", attendeeData.firstNameValue);
cell.textLabel.text = attendeeData.firstNameValue;
}

Search Bar and Search Display, unrecognized selector sent to instance

I have a problem with a searchBar, i get an error unrecognized selector.
2013-02-11 14:48:27.211 Scores (FREE)[13946:c07] test ijsid
CONTAINS[cd] "A" 2013-02-11 14:48:27.213 Scores (FREE)[13946:c07] test
(
Axel,
"Double Axel",
"Triple Axel",
"Quad Axel" ) 2013-02-11 14:48:27.213 Scores (FREE)[13946:c07] -[SingleElements isEqualToString:]: unrecognized selector sent to instance 0x755a5f0 2013-02-11 14:48:27.214 Scores (FREE)[13946:c07]
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SingleElements
isEqualToString:]: unrecognized selector sent to instance 0x755a5f0'
* First throw call stack: (0x209f012 0x11ace7e 0x212a4bd 0x208ebbc 0x208e94e 0x249e9f 0x24a064 0x2ae4 0x1ab8fb 0x1ab9cf 0x1941bb 0x192872
0x19d701 0x1a5d5d 0x1ade04 0x3d55f5 0x3d809e 0x327cc5 0x11c0705
0xf4213 0x1b5c7e 0x1b5310 0x1c213c 0x1cc5a6 0xc6d4f9 0x20f90c5
0x2053efa 0xba1bb2 0x38a39de 0x29f11da 0x2e2adfc 0x2e2dbf8 0x387e612
0x387e74a 0x387eec0 0x387ecb8 0x387e204 0x2c6c22b 0x2c6c193 0x3850e96
0x387d4cc 0x2e28136 0x2e273c6 0x2e5a980 0x34b67fd 0x2e51576 0x2e526da
0x2e5072e 0x34b4eaa 0x2e6aaf1 0x2e5a72a 0x2e2e6ae 0x2a2d62b 0x11c06b0
0x3899810 0x2a6c1a4 0x2a6e2ff 0x2b20b4 0x274aef 0x275e58 0x2749fe
0x27ed29 0x101ddb 0x1ff7f5 0x1ff7f5 0x1ff7f5 0x1ff7f5 0x1ff7f5
0x1ff7f5 0x1ff7f5 0x1ff7f5 0x1ff7f5 0x101e35 0x101806 0x101beb 0xf3698
0x1ffadf9 0x1ffaad0 0x2014bf5 0x2014962 0x2045bb6 0x2044f44 0x2044e1b
0x1ff97e3 0x1ff9668 0xf0ffc 0x1f8d 0x1eb5) libc++abi.dylib: terminate
called throwing an exception
(lldb) po 0x755a5f0 $0 = 123053552 Axel
.h
#interface SingleElementsVC : UITableViewController{
NSMutableArray *thesingleelementslist;
sqlite3 * db;
UISearchDisplayController *searchDisplayController;
UISearchDisplayController *searchBar;
NSMutableArray *searchResults;
}
#property(nonatomic,retain) NSMutableArray *thesingleelementslist;
#property(nonatomic, strong)SingleElementsDetailView *details;
-(NSMutableArray *) singleElementsList;
#property (nonatomic, retain) IBOutlet UISearchDisplayController *searchDisplayController;
#property (nonatomic, retain) IBOutlet UISearchDisplayController *searchBar;
#property (nonatomic, copy) NSMutableArray *searchResults;
#end
.m
#interface SingleElementsVC ()
#end
#implementation SingleElementsVC
#synthesize thesingleelementslist;
#synthesize searchDisplayController;
#synthesize searchBar;
#synthesize searchResults;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[self singleElementsList];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (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 == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *sectionHeader = nil;
sectionHeader = #"Scale Of Values For Single";
return sectionHeader;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSInteger rows = 0;
if ([tableView
isEqual:self.searchDisplayController.searchResultsTableView]){
rows = [self.searchResults count];
}
else{
rows = [self.thesingleelementslist count];
}
return rows;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"SingleElementsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){
cell.textLabel.text = [self.searchResults objectAtIndex:indexPath.row];
}
else{
SingleElements *singleElements = [self.thesingleelementslist objectAtIndex:indexPath.row];
cell.textLabel.text = singleElements.ijsid;
NSString *singleElementsDescriptionAndBase = [NSString stringWithFormat:#"%# (%#)",singleElements.description, singleElements.base];
cell.detailTextLabel.text = singleElementsDescriptionAndBase;
}
return cell;
}
-(NSMutableArray *) singleElementsList{
thesingleelementslist = [[NSMutableArray alloc] initWithCapacity:10];
#try {
NSFileManager *fileMgr = [NSFileManager defaultManager];
NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:#"ElementsDb.sqlite"];
BOOL success = [fileMgr fileExistsAtPath:dbPath];
if(!success)
{
NSLog(#"Cannot locate database file '%#'.", dbPath);
}
if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK))
{
NSLog(#"An error has occured: %s", sqlite3_errmsg(db));
}
const char *sql = "SELECT * FROM single";
sqlite3_stmt *sqlStatement;
if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK)
{
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}else{
while (sqlite3_step(sqlStatement)==SQLITE_ROW) {
SingleElements * singleElements = [[SingleElements alloc] init];
singleElements.group = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,1)];
singleElements.ijsid = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)];
singleElements.description = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,3)];
singleElements.plus3 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,4)];
singleElements.plus2 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,5)];
singleElements.plus1 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,6)];
singleElements.base = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,7)];
singleElements.baseur = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,8)];
singleElements.minus1 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,9)];
singleElements.minus2 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,10)];
singleElements.minus3 = [[NSDecimalNumber alloc] initWithDouble:sqlite3_column_double(sqlStatement,11)];
singleElements.goeplus3 = [singleElements.plus3 decimalNumberByAdding:singleElements.base];
singleElements.goeplus2 = [singleElements.plus2 decimalNumberByAdding:singleElements.base];
singleElements.goeplus1 = [singleElements.plus1 decimalNumberByAdding:singleElements.base];
singleElements.goeminus1 = [singleElements.minus1 decimalNumberByAdding:singleElements.base];
singleElements.goeminus2 = [singleElements.minus2 decimalNumberByAdding:singleElements.base];
singleElements.goeminus3 = [singleElements.minus3 decimalNumberByAdding:singleElements.base];
[thesingleelementslist addObject:singleElements];
}
}
}
#catch (NSException *exception) {
NSLog(#"Problem with prepare statement: %s", sqlite3_errmsg(db));
}
#finally {
sqlite3_close(db);
return thesingleelementslist;
}
}
- (void)filterContentForSearchText:(NSString*)searchText
scope:(NSString*)scope
{
NSPredicate *resultPredicate = [NSPredicate
predicateWithFormat:#"ijsid contains[cd] %#",
searchText];
self.searchResults = [NSMutableArray arrayWithArray:[self.thesingleelementslist filteredArrayUsingPredicate:resultPredicate]];
NSLog(#"test %#", searchResults);
}
#pragma mark - UISearchDisplayController delegate methods
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
return YES;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
[self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles] objectAtIndex:searchOption]];
return YES;
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//if ([[segue identifier] isEqualToString:#"showDetail"]) {
SingleElementsDetailView *detailViewController = [segue destinationViewController];
SingleElements *singleElements = [[SingleElements alloc]init];
detailViewController.singleElements = [self.singleElementsList objectAtIndex:[self.tableView indexPathForSelectedRow].row];
singleElements = [self.singleElementsList objectAtIndex:[self.tableView indexPathForSelectedRow].row];
NSLog(#"test %#", singleElements.ijsid);
NSLog(#"test %#", singleElements.description);
NSLog(#"test %#", singleElements.goeplus3);
NSLog(#"test %#", singleElements.goeplus2);
NSLog(#"test %#", singleElements.goeplus1);
NSLog(#"test %#", singleElements.base);
NSLog(#"test %#", singleElements.goeminus1);
NSLog(#"test %#", singleElements.goeminus2);
NSLog(#"test %#", singleElements.goeminus3);
//}
}
#end
Class SingleElements.h
#interface SingleElements : NSObject{
NSString *group;
NSString *ijsid;
NSString *description;
NSDecimalNumber *plus3;
NSDecimalNumber *plus2;
NSDecimalNumber *plus1;
NSDecimalNumber *base;
NSDecimalNumber *baseur;
NSDecimalNumber *minus1;
NSDecimalNumber *minus2;
NSDecimalNumber *minus3;
NSDecimalNumber *goeplus3;
NSDecimalNumber *goeplus2;
NSDecimalNumber *goeplus1;
NSDecimalNumber *goeminus1;
NSDecimalNumber *goeminus2;
NSDecimalNumber *goeminus3;
}
#property(nonatomic,copy) NSString *group;
#property(nonatomic,copy) NSString *ijsid;
#property(nonatomic,copy) NSString *description;
#property(nonatomic,copy) NSDecimalNumber *plus3;
#property(nonatomic,copy) NSDecimalNumber *plus2;
#property(nonatomic,copy) NSDecimalNumber *plus1;
#property(nonatomic,copy) NSDecimalNumber *base;
#property(nonatomic,copy) NSDecimalNumber *baseur;
#property(nonatomic,copy) NSDecimalNumber *minus1;
#property(nonatomic,copy) NSDecimalNumber *minus2;
#property(nonatomic,copy) NSDecimalNumber *minus3;
#property(nonatomic,copy) NSDecimalNumber *goeplus3;
#property(nonatomic,copy) NSDecimalNumber *goeplus2;
#property(nonatomic,copy) NSDecimalNumber *goeplus1;
#property(nonatomic,copy) NSDecimalNumber *goeminus1;
#property(nonatomic,copy) NSDecimalNumber *goeminus2;
#property(nonatomic,copy) NSDecimalNumber *goeminus3;
#end
Any help are welcome, thanks.
Is SingleElements subclass of NSString ??
My guess would be isEqualToString is not available for SingleElements.
Can you post code for SingleElements class?
EDIT:
From your updated question I can see that it's a subclass of NSObject which hasn't any idea with what isEqualToString has to do with.
For getting to the line of crash (which you will not have any clue, If I guessed it right), Try to do as following:
Go to the breakpoints navigator in the left pane.
Click the plus button at the bottom of the screen.
Choose Add Exception Breakpoint
In the bubble that pops up choose Objective-C in the Exception field.
Execute the program again
Now, Try to have that exception again. XCode will bring you to that line before crashing.
Then, Post that line here. May be then, We can go for the solution.

Resources