Search is not working - iphone

I'm trying to do search but its not working for me perfectly .What i need that when I enter B then i should get all the words that starts with B . I'm still wondering where i'm doing wrong. i'm very new to ios.
here is my code :-
ContactViewController.h
#import <UIKit/UIKit.h>
#interface ContactViewController :
UIViewController<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>
{
UISearchBar* searchBar;
IBOutlet UITableView* contactTableView;
NSMutableArray *listOfItems;
NSMutableArray *copyListOfItems;
NSArray *content;
NSArray *indices;
NSArray* contacts;
BOOL searching;
BOOL letUserSelectRow;
}
-(void)btn_AddContact;
#end
ContactViewController.m
#import "ContactViewController.h"
#import "AddContactsViewController.h"
#import "CustomCell.h"
#import "DataGenerator.h"
#interface ContactViewController ()
#end
#implementation ContactViewController
- (void)viewDidLoad
{
[super viewDidLoad];
const NSInteger searchBarHeight = 45;
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320,
searchBarHeight)];
[self.view addSubview:searchBar];
searchBar.delegate = self;
[self.view addSubview:searchBar];
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:#"Refresh"
style:UIBarButtonItemStyleBordered target:self action:#selector(onAddContact)];
self.navigationItem.rightBarButtonItem = addButton;
UILabel *label = [[UILabel alloc] initWithFrame:CGRectZero];
label.backgroundColor = [UIColor clearColor];
label.font = [UIFont boldSystemFontOfSize:20.0];
label.shadowColor = [UIColor colorWithWhite:0.0 alpha:0.5];
label.textAlignment = UITextAlignmentCenter;
label.textColor = [UIColor whiteColor]; // change this color
self.navigationItem.titleView = label;
label.text = NSLocalizedString(#"All Contacts", #"");
[label sizeToFit];
content = [DataGenerator wordsFromLetters];
indices = [[content valueForKey:#"headerTitle"] retain];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [content count];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section {
return [[[content objectAtIndex:section] objectForKey:#"rowValues"] 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:UITableViewCellStyleSubtitle
reuseIdentifier:CellIdentifier];
}
if(searching) {
cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
cell.detailTextLabel.text=[NSString stringWithFormat:#"%# %# %#",
#"pauline.abraham#gmail.com", #" |",#"123456777"] ;
}else {
cell.textLabel.text = [[[content objectAtIndex:indexPath.section]
objectForKey:#"rowValues"]
objectAtIndex:indexPath.row];
//cell.detailTextLabel.numberOfLines=2;
//cell.detailTextLabel.lineBreakMode=NSLineBreakByWordWrapping;
cell.detailTextLabel.text=[NSString stringWithFormat:#"%# %# %#",
#"pauline.abraham#gmail.com", #" |",#"123456777"] ;
}
return cell;
}
- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:
(NSInteger)section {
return [[content objectAtIndex:section] objectForKey:#"headerTitle"];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [content valueForKey:#"headerTitle"];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:
(NSString *)title atIndex:(NSInteger)index {
return [indices indexOfObject:title];
}
-(void)onAddContact
{
// AddContactsViewController* add = [[AddContactsViewController alloc]
initWithNibName:#"AddContactsViewController" bundle:nil];
// [self.navigationController pushViewController:add animated:YES];
}
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
if(searching)
return;
searching = YES;
letUserSelectRow = NO;
[contactTableView setScrollEnabled:NO];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self
action:#selector(btn_DoneSearch)];
}
-(void)btn_DoneSearch
{
searchBar.text = #"";
[searchBar resignFirstResponder];
searching = NO;
letUserSelectRow = YES;
[contactTableView setScrollEnabled:YES];
self.navigationItem.rightBarButtonItem = nil;
[contactTableView reloadData];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
//Remove all objects first.
[copyListOfItems removeAllObjects];
if([searchText length] > 0){
searching = YES;
letUserSelectRow = YES;
[contactTableView setScrollEnabled:YES];
[self searchTableView];
}else {
searching = NO;
letUserSelectRow = NO;
[contactTableView setScrollEnabled:NO];
}
[contactTableView reloadData];
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[self searchTableView];
}
-(void)searchTableView
{
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in content)
{
NSArray *array = [dictionary objectForKey:#"rowValues"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText
options:NSCaseInsensitiveSearch];
if (titleResultsRange.length>0)
{
[copyListOfItems addObject:sTemp];
NSLog(#"lenght : %d",titleResultsRange.length );
}
}
searchArray = nil;
}
#end

see this below code also you not add the rows related searched data put this condition in below 3 delegate method of UITableView also
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (searching)
return 1;
else
return [content count];
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (searching)
return [copyListOfItems count];
else
return [[[content objectAtIndex:section] objectForKey:#"rowValues"] count] ;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(searching)
return #"";
else
return [[content objectAtIndex:section] objectForKey:#"headerTitle"];
}

Related

indexing not working in tableview

i am trying to achieve indexing on table for that i use following method indexing appears on right side but it is not working code is below
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 2;
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z|#"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
int foundIndex = 0;
for (int i = 0; i< [mainArray count]; i++) {
// Here you return the name i.e. Honda,Mazda
// and match the title for first letter of name
// and move to that row corresponding to that indexpath as below
NSString *letterString = [[[mainArray valueForKey:#"name"] objectAtIndex:i] substringToIndex:1];
NSLog(#"letterString%#",letterString);
NSLog(#"title%#",title);
if ([[letterString uppercaseString ] compare:title] == NSOrderedDescending){
break;
foundIndex++; }
if(foundIndex > mainArray.count)
foundIndex = mainArray.count;
[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return 1;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return 120;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
//—set the text to display for the cell—
NSLog(#"%d",mainArray.count);
NSLog(#"%#",mainArray);
UIImageView *selectionView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 768, 120)];
UIImage *image = [UIImage imageNamed:#"default.png"];
UIImageView* blockView = [[UIImageView alloc] initWithImage:image];
blockView.layer.cornerRadius = 4;
blockView.layer.masksToBounds = YES;
blockView.layer.borderWidth = 2;
blockView.layer.borderColor = [UIColor blackColor].CGColor;
blockView.frame = CGRectMake(5, 5, 110, 110);
// title isKindOfClass:[NSNull class]])
//NSLog(#"%#",[[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]]);
id obj = [[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]];
if ([obj isKindOfClass:[NSString class]])
{
[selectionView addSubview:blockView];
}
else {
UIImage *contactImage = [[UIImage alloc]init];
contactImage = [[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]];
// NSLog(#" array%#",[[mainArray valueForKey:#"image"] objectAtIndex:[indexPath row]]);
NSLog(#" image%#",contactImage);
UIImageView *blockView = [[UIImageView alloc] initWithImage:contactImage];
blockView.frame = CGRectMake(5, 5, 110, 110);
blockView.layer.cornerRadius = 4;
blockView.layer.masksToBounds = YES;
blockView.layer.borderWidth = 2;
blockView.layer.borderColor = [UIColor blackColor].CGColor;
[selectionView addSubview:blockView];
}
NSLog(#" name :%#",[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]]);
if ([[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]] isEqualToString:#"(null)"]) {
UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
name.text =#"Name Not Available";
[name setBackgroundColor:[UIColor clearColor]];
[ name setFont:[UIFont fontWithName:#"Arial-BoldMT" size:30]];
name.textColor = [UIColor whiteColor];
[selectionView addSubview:name];
}
else{
UILabel *name = [[UILabel alloc]initWithFrame:CGRectMake(130, 10, 310, 55)];
name.text =[[mainArray valueForKey:#"name"] objectAtIndex:[indexPath row]];
[name setBackgroundColor:[UIColor clearColor]];
[ name setFont:[UIFont fontWithName:#"Arial-BoldMT" size:30]];
name.textColor = [UIColor whiteColor];
[selectionView addSubview:name];
}
if ([[[mainArray valueForKey:#"phone"] objectAtIndex:[indexPath row]] isEqualToString:#"Add Number"]) {
UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
phone.text =#"Not Available";
[phone setBackgroundColor:[UIColor clearColor]];
[ phone setFont:[UIFont fontWithName:#"Arial-BoldMT" size:25]];
phone.textColor = [UIColor whiteColor];
[selectionView addSubview:phone];
}
else{
UILabel *phone = [[UILabel alloc]initWithFrame:CGRectMake(130, 70, 300, 50)];
phone.text =[[mainArray valueForKey:#"phone"] objectAtIndex:[indexPath row]];
[phone setBackgroundColor:[UIColor clearColor]];
[ phone setFont:[UIFont fontWithName:#"Arial-BoldMT" size:25]];
phone.textColor = [UIColor whiteColor];
[selectionView addSubview:phone];
}
if ([[[mainArray valueForKey:#"email"] objectAtIndex:[indexPath row]] isEqualToString:#"Add Email"]) {
UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
email.text =#"Email Id Not Available";
[email setBackgroundColor:[UIColor clearColor]];
[ email setFont:[UIFont fontWithName:#"Arial-BoldMT" size:20]];
email.textColor = [UIColor whiteColor];
[selectionView addSubview:email];
}
else{
UILabel *email = [[UILabel alloc]initWithFrame:CGRectMake(420, 40, 350, 50)];
email.text =[[mainArray valueForKey:#"email"] objectAtIndex:[indexPath row]];
[email setBackgroundColor:[UIColor clearColor]];
[ email setFont:[UIFont fontWithName:#"Arial-BoldMT" size:20]];
email.textColor = [UIColor whiteColor];
[selectionView addSubview:email];
}
[[cell contentView] addSubview:selectionView];
return cell;
}
what problem i face is it reach top of the table when i click any index and not right index
To use the index your table should really be broken into sections. It looks like currently you are asking the framework to scroll to a specified row and then to scroll to the top of section 0 immediately afterwards.
It may work if you use performSelector to request the scroll after a short delay (it may look nasty). Or possibly if you return -1 from the method (documentation does not support this guess).
The answer really is to use sections in your table and let the framework work as designed.
when we have section 0 then we can do like this
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
NSArray *toBeReturned = [NSArray arrayWithArray:
[#"A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z"
componentsSeparatedByString:#"|"]];
return toBeReturned;
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
int foundIndex = 0;
for (int i = 0; i< [mainArray count]; i++) {
NSString *letterString = [[[mainArray valueForKey:#"name"] objectAtIndex:i] substringToIndex:1];
NSLog(#"letterString%#",letterString);
NSLog(#"title%#",title);
if ([letterString caseInsensitiveCompare:title] == NSOrderedSame)
{
break;
}
else{
foundIndex++;
NSLog(#"founded index %d",foundIndex);
}
}
NSLog(#"founded index %d",mainArray.count);
NSLog(#"founded index %d",foundIndex);
if(foundIndex >= mainArray.count){
foundIndex = mainArray.count-1;
}
NSLog(#"founded index %d",foundIndex);
[table scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:foundIndex inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return 1;
}
.h
#import <TapkuLibrary/TapkuLibrary.h>
#import <UIKit/UIKit.h>
#import <EventKit/EventKit.h>
#interface CalendarMonthViewController : TKCalendarMonthTableViewController{
NSMutableArray *events;
EKEventStore *eventStore;
NSDate *startDatee;
NSDate *lastDatee;
}
#property (strong,nonatomic) NSMutableArray *dataArray;
#property (strong,nonatomic) NSMutableDictionary *dataDictionary;
- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end;
#end
.m
#import "CalendarMonthViewController.h"
#import "AppDelegate.h"
#implementation CalendarMonthViewController
#pragma mark - View Lifecycle
- (void) viewDidLoad{
[super viewDidLoad];
[self.monthView selectDate:[NSDate month]];
}
-(void)viewWillAppear:(BOOL)animated{
[self updateTableOffset:YES];
NSLog(#"hi ha ");
}
-(void)fatchAllEvent{
eventStore = [[EKEventStore alloc] init];
if ([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
__block typeof (self) weakSelf = self; // replace __block with __weak if you are using ARC
dispatch_async(dispatch_get_main_queue(), ^{
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSLog(#" granted");
[weakSelf performSelectorOnMainThread:#selector(allCalendarEvent) withObject:nil waitUntilDone:YES];
}
else
{
NSLog(#"Not granted");
}
}];
});
}
else
{
[self allCalendarEvent];
}
}
-(void)allCalendarEvent{
NSDate *startDate = [NSDate distantPast];
NSDate *endDate = [NSDate distantFuture];
// use Dictionary for remove duplicates produced by events covered more one year segment
NSMutableDictionary *eventsDict = [NSMutableDictionary dictionaryWithCapacity:1024];
NSDate* currentStart = [NSDate dateWithTimeInterval:0 sinceDate:startDate];
int seconds_in_year = 60*60*24*365;
// enumerate events by one year segment because iOS do not support predicate longer than 4 year !
while ([currentStart compare:endDate] == NSOrderedAscending) {
NSDate* currentFinish = [NSDate dateWithTimeInterval:seconds_in_year sinceDate:currentStart];
if ([currentFinish compare:endDate] == NSOrderedDescending) {
currentFinish = [NSDate dateWithTimeInterval:0 sinceDate:endDate];
}
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:currentStart endDate:currentFinish calendars:nil];
[eventStore enumerateEventsMatchingPredicate:predicate
usingBlock:^(EKEvent *event, BOOL *stop) {
if (event) {
[eventsDict setObject:event forKey:event.eventIdentifier];
}
}];
currentStart = [NSDate dateWithTimeInterval:(seconds_in_year + 1) sinceDate:currentStart];
}
events = [[NSMutableArray alloc]init];
for (id key in eventsDict) {
id anObject = [eventsDict objectForKey:key];
[events addObject:anObject];
/* Do something with anObject. */
}
NSLog(#"all event %#",events);
CFRunLoopStop(CFRunLoopGetCurrent());
// NSLog(#"all event crash%#",events);
}
#pragma mark - MonthView Delegate & DataSource
- (NSArray*) calendarMonthView:(TKCalendarMonthView*)monthView marksFromDate:(NSDate*)startDate toDate:(NSDate*)lastDate{
if (!events) {
[self fatchAllEvent];
CFRunLoopRun();
}
NSLog(#"all event %#",events);
[self generateRandomDataForStartDate:startDate endDate:lastDate];
// NSLog(#"%#",self.dataDictionary);
NSLog(#"%#",self.dataArray);
NSLog(#"%#",self.dataDictionary);
NSLog(#"%#",[self.dataDictionary allKeys]);
return self.dataArray;
}
- (void) calendarMonthView:(TKCalendarMonthView*)monthView didSelectDate:(NSDate*)date{
// CHANGE THE DATE TO YOUR TIMEZONE
TKDateInformation info = [date dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *myTimeZoneDay = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone systemTimeZone]];
NSLog(#"Date Selected: %#",myTimeZoneDay);
[self.tableView reloadData];
}
- (void) calendarMonthView:(TKCalendarMonthView*)mv monthDidChange:(NSDate*)d animated:(BOOL)animated{
[super calendarMonthView:mv monthDidChange:d animated:animated];
[self.tableView reloadData];
}
#pragma mark - UITableView Delegate & DataSource
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
if ([[UIDevice currentDevice] userInterfaceIdiom]==UIUserInterfaceIdiomPad)
{
NSArray *views =[[NSBundle mainBundle] loadNibNamed:#"CalendarTableHeader" owner:nil options:nil];
UIView *headerView=[views objectAtIndex:0];
return headerView;
}
else
{
return nil;
}
}
- (CGFloat) tableView:(UITableView *) tableView heightForHeaderInSection:(NSInteger) section {
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
return 25;
} else {
return 0;
}
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
if(ar == nil) return 0;
return [ar count];
}
- (UITableViewCell *) tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
NSArray *ar = [self.dataDictionary objectForKey:[self.monthView dateSelected]];
cell.textLabel.text = [ar objectAtIndex:indexPath.row];
return cell;
}
- (BOOL)isDate:(NSDate *)date inRangeFirstDate:(NSDate *)firstDate lastDate:(NSDate *)lastDate {
return [date compare:firstDate] == NSOrderedDescending &&
[date compare:lastDate] == NSOrderedAscending;
}
- (void) generateRandomDataForStartDate:(NSDate*)start endDate:(NSDate*)end{
// this function sets up dataArray & dataDictionary
// dataArray: has boolean markers for each day to pass to the calendar view (via the delegate function)
// dataDictionary: has items that are associated with date keys (for tableview)
NSMutableArray *arrayOfDates = [[NSMutableArray alloc ]init];
NSMutableArray *arrayOfNames = [[NSMutableArray alloc ]init];
// NSLog(#"Delegate Range: %# %# %d",start,end,[start daysBetweenDate:end]);
NSDateFormatter *newformater=[[[NSDateFormatter alloc]init]autorelease];
[newformater setDateFormat:#"yyyy-MM-dd HH:mm:ss "];
NSDate *startD = [newformater dateFromString:[newformater stringFromDate:start]];
NSDate *endD = [newformater dateFromString:[newformater stringFromDate:end]];
NSLog(#"%#",events);
BOOL isAttempt = NO;
for (int i =0; i<arrayOfDates.count; i++) {
if ([start isEqualToDate:[arrayOfDates objectAtIndex:i]]) {
[self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:start];
[self.dataArray addObject:[NSNumber numberWithBool:YES]];
isAttempt = YES;
}
else{
isAttempt = NO;
}
}
if (!isAttempt) {
[self.dataArray addObject:[NSNumber numberWithBool:NO]];
}
for (int i = 0; i<events.count; i++) {
NSDate *eventDate = [[events valueForKey:#"startDate"] objectAtIndex:i];
NSString *eventName = [[events valueForKey:#"title"]objectAtIndex:i];
NSLog(#"startreal%#",start);
NSLog(#"endreal%#",end);
NSLog(#"eventName:::%#",eventName);
NSLog(#"start%#",startD);
NSLog(#"end%#",endD);
NSLog(#"eventDate%#",eventDate);
if([self isDate:eventDate inRangeFirstDate:startD lastDate:endD]){
[arrayOfDates addObject:eventDate];
[arrayOfNames addObject:eventName];
}else{
}
}
NSLog(#"eventdate = %#",arrayOfDates);
NSLog(#"eventName = %#",arrayOfNames);
// the dates that we have will go thorought for loop and we wil check if its between start and end date then we will add that object to datadictionary or wont
[self.dataArray removeAllObjects];
[self.dataDictionary removeAllObjects];
self.dataArray = [NSMutableArray array];
self.dataDictionary = [NSMutableDictionary dictionary];
NSDate *d = start;
while(YES){
BOOL isAttempt = NO;
for (int i =0; i<arrayOfDates.count; i++) {
if ([d isEqualToDate:[arrayOfDates objectAtIndex:i]]) {
[self.dataDictionary setObject:[NSArray arrayWithObjects:[arrayOfNames objectAtIndex:i],nil] forKey:d];
[self.dataArray addObject:[NSNumber numberWithBool:YES]];
isAttempt = YES;
}
else{
isAttempt = NO;
}
}
if (!isAttempt) {
[self.dataArray addObject:[NSNumber numberWithBool:NO]];
}
TKDateInformation info = [d dateInformationWithTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
info.day++;
d = [NSDate dateFromDateInformation:info timeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
if([d compare:end]==NSOrderedDescending) break;
}
}
-(void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
{
[self updateTableOffset:YES];
}
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
#end

RSS parsing errors iPhone

I am building something that includes an RSS reader. Everything seems to work fine, except in every description (grabbed from the RSS feed using the code below), before the description, there is a "" How do I remove that?
#import "RSSItem.h"
#import "GTMNSString+HTML.h"
#implementation RSSItem
-(NSAttributedString*)cellMessage
{
if (_cellMessage!=nil) return _cellMessage;
NSDictionary* boldStyle = #{NSFontAttributeName: [UIFont fontWithName:#"Helvetica-Bold" size:16.0]};
NSDictionary* normalStyle = #{NSFontAttributeName: [UIFont fontWithName:#"Helvetica" size:16.0]};
NSMutableAttributedString* articleAbstract = [[NSMutableAttributedString alloc] initWithString:self.title];
[articleAbstract setAttributes:boldStyle
range:NSMakeRange(0, self.title.length)];
[articleAbstract appendAttributedString:
[[NSAttributedString alloc] initWithString:#"\n\n"]
];
int startIndex = [articleAbstract length];
NSString* description = [NSString stringWithFormat:#"%#<p><p><em>...", [self.description substringToIndex:200]];
description = [description gtm_stringByUnescapingFromHTML];
[articleAbstract appendAttributedString:
[[NSAttributedString alloc] initWithString: description]
];
[articleAbstract setAttributes:normalStyle
range:NSMakeRange(startIndex, articleAbstract.length - startIndex)];
_cellMessage = articleAbstract;
return _cellMessage;
}
#end
And this is the code for the MasterViewController.m file which displays the RSS feed:
#import "MasterViewController.h"
#import "DetailViewController.h"
#import "TableHeaderView.h"
#import "RSSLoader.h"
#import "RSSItem.h"
#interface MasterViewController () {
NSArray *_objects;
NSURL* feedURL;
UIRefreshControl* refreshControl;
}
#end
#implementation MasterViewController
-(void)refreshFeed
{
RSSLoader* rss = [[RSSLoader alloc] init];
[rss fetchRssWithURL:feedURL
complete:^(NSString *title, NSArray *results) {
dispatch_async(dispatch_get_main_queue(), ^{
[(TableHeaderView*)self.tableView.tableHeaderView setText:title];
_objects = results;
[self.tableView reloadData];
[refreshControl endRefreshing];
});
}];
}
-(void)viewDidLoad
{
[super viewDidLoad];
feedURL = [NSURL URLWithString:#"http://pipes.yahoo.com/pipes/pipe.run?_id=c47dcdc375e72c5ad08f3470eea6afa0&_render=rss"];
refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self
action:#selector(refreshInvoked:forState:)
forControlEvents:UIControlEventValueChanged];
[self.tableView addSubview: refreshControl];
[self refreshFeed];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
RSSItem *item = [_objects objectAtIndex:indexPath.row];
CGRect cellMessageRect = [item.cellMessage boundingRectWithSize:CGSizeMake(200,10000)
options:NSStringDrawingUsesLineFragmentOrigin
context:nil];
return cellMessageRect.size.height;
}
-(void) refreshInvoked:(id)sender forState:(UIControlState)state {
[self refreshFeed];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
RSSItem *object = _objects[indexPath.row];
cell.textLabel.attributedText = object.cellMessage;
cell.textLabel.numberOfLines = 5;
return cell;
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
RSSItem *object = _objects[indexPath.row];
self.detailViewController.detailItem = object;
}
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"showDetail"]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
NSDate *object = _objects[indexPath.row];
[[segue destinationViewController] setDetailItem:object];
}
}
-(IBAction)btn_regPressed:(id)sender
{
NSLog(#"start to dissmis modal");
[self dismissViewControllerAnimated:YES completion:nil];
}
#end
Any ideas what is happening?
Replace the following code:
NSString* description = [NSString stringWithFormat:#"%#<p><p><em>...", [self.description substringToIndex:200]];
With:
NSString* description = [[NSString stringWithFormat:#"%#<p><p><em>...", [self.description substringToIndex:200]] stringByReplacingOccurrencesOfString:#"\"" withString:#""];

I have big delay using search in my UITableView

There is my problem, i have an application which have decent amount of data. My .plist file contain array of elements, it looks like this - Orange, proteins - 25, carbs - 40, fat - 50, etc.. Totally, each item contain 7 rows of sub-rows with data.
My tableview show all array displayed with sections, in one big massive tableview. In top of screen i have a search bar. When i tap search bar, and enter any letter, it show new array like this - M: Big Mac, Meat, Meals, etc.
So, before i reach 700+ elements in my array everything was just fine, but, when i added last 500 elements (my .plist file edited from 200 to 700 elements), i realize that when i tap search and enter any letter, i have big delay. First delay about 0,6 sec (when i tap search field), second delay after i press button in my keyboard (about 0,6 sec again). I think, that is because i add many items to my .plist.
Obviously, i don't want to reduce number of my objects in array. I guess i have "bad" code, and i ask you for any helpful advice. Please help me, i guess i need to improve it! There is my code, that contain my UITableView code and Search methods:
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:#"bg.png"]];
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:#"food.plist"];
listOfItems = [[NSMutableArray alloc]initWithContentsOfFile:path];
searchListOfItems = [[NSMutableArray alloc]init];
searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, 320, 45)];
searchBar.barStyle = UIBarStyleBlackTranslucent;
searchBar.showsCancelButton = NO;
searchBar.autocorrectionType=UITextAutocorrectionTypeNo;
searchBar.autocapitalizationType=UITextAutocapitalizationTypeNone;
searchBar.delegate= self;
[[self tableView] setTableHeaderView:searchBar];
searching = NO;
letUserSelectRow = YES;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(addProduct:)];
self.navigationItem.leftBarButtonItem = addButton;
self.navigationItem.backBarButtonItem.title = #"Back";
[self.tableView reloadData];
self.navigationItem.backBarButtonItem =
[[UIBarButtonItem alloc] initWithTitle:#"Назад"
style:UIBarButtonItemStyleBordered
target:nil
action:nil];
self.title = #"Продукты";
UILabel* tlabel=[[UILabel alloc] initWithFrame:CGRectMake(0,0, 125, 21)];
tlabel.text=self.navigationItem.title;
tlabel.font = [UIFont fontWithName:#"Chalkboard SE" size:17];
tlabel.textAlignment = UITextAlignmentCenter;
tlabel.textColor=[UIColor whiteColor];
tlabel.backgroundColor =[UIColor clearColor];
tlabel.adjustsFontSizeToFitWidth=YES;
self.navigationItem.titleView=tlabel;
}
- (void)hideModalViewController:(NSNotification *)notif
{
[self dismissModalViewControllerAnimated:YES];
[self viewDidLoad];
}
-(void)productAdded {
[self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height - self.tableView.frame.size.height)];
[self.tableView reloadData];
}
- (void)addProduct:(UIBarButtonItem *)button
{
BIDAddProductViewController *addProductVC = [[BIDAddProductViewController alloc]init];
addProductVC.delegate = self;
[self.navigationController pushViewController:addProductVC animated:YES];
[[NSNotificationCenter defaultCenter]addObserver:self selector:#selector(hideModalViewController:) name:#"HideModalViewController" object:addProductVC];
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.childController = nil;
self.tableView=nil;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject]stringByAppendingPathComponent:#"food.plist"];
NSMutableArray *listOfItemsToDelete = [[NSMutableArray alloc]initWithContentsOfFile:path];
[[[listOfItemsToDelete objectAtIndex:indexPath.section]objectForKey:#"Products"] removeObjectAtIndex:indexPath.row];
[listOfItemsToDelete writeToFile:path atomically:YES];
[self viewDidLoad];
NSArray *descriptionsArray = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"ProductName"];
NSLog(#"%#", descriptionsArray);
NSLog(#"%i", [descriptionsArray count]);
if ([descriptionsArray count]<2){
[listOfItems removeObjectAtIndex:indexPath.section];
[tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:NO];
[listOfItems writeToFile:path atomically:YES];
}
}
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
return UITableViewCellEditingStyleDelete;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *SectionsTableIdentifier = #"SectionsTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
SectionsTableIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:SectionsTableIdentifier];
}
if(searching)
cell.textLabel.text = [[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"ProductName"];
else {
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *array = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"ProductName"];
NSString *cellValue = [array objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
}
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (searching)
return 1;
else
return [listOfItems count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (searching)
return [searchListOfItems count];
else {
NSDictionary *dictionary = [listOfItems objectAtIndex:section];
NSArray *array = [dictionary objectForKey:#"Products"];
return [array count];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if(searching)
return #"";
return [[listOfItems objectAtIndex:section]valueForKey:#"SectionName"];
}
- (void) doneSearching_Clicked:(id)sender {
searchBar.text = #"";
[searchBar resignFirstResponder];
letUserSelectRow = YES;
searching = NO;
self.navigationItem.rightBarButtonItem = nil;
self.tableView.scrollEnabled = YES;
[self.tableView reloadData];
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
[self searchTableView];
}
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSArray *array = [dictionary objectForKey:#"Products"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in [searchArray valueForKeyPath:#"ProductName"] )
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[searchListOfItems addObject:[searchArray objectAtIndex:[[searchArray valueForKeyPath:#"ProductName"]indexOfObject:sTemp]]];
}
searchArray = nil;
}
- (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(letUserSelectRow)
return indexPath;
else
return nil;
}
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
searching = YES;
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(doneSearching_Clicked:)];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
[searchListOfItems removeAllObjects];
if([searchText length] > 0) {
searching = YES;
letUserSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self searchTableView];
}
else {
searching = NO;
letUserSelectRow = NO;
self.tableView.scrollEnabled = NO;
}
[self.tableView reloadData];
}
- (void)viewWillAppear:(BOOL)animated
{
letUserSelectRow = YES;
[super viewWillAppear:animated];
}
#pragma mark -
#pragma mark Table Delegate Methods
- (void)tableView:(UITableView *)tableView
didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (childController == nil) {
childController = [[BIDDisclosureDetailController alloc]
initWithNibName:#"BIDDisclosureDetail" bundle:nil];
}
if(searching)
{
childController.description = [[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"ProductName"];
// childController.title = [[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"ProductName"];
childController.calories = [[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"Calories"];
childController.protein = [[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"Proteins"];
childController.carbohydrates = [[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"Carbohydrates"];
childController.fat = [[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"Fat"];
childController.myBool=[[searchListOfItems objectAtIndex:indexPath.row]valueForKey:#"TextField"];
}
else
{
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section];
NSArray *descriptionsArray = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"ProductName"];
childController.description = [descriptionsArray objectAtIndex:indexPath.row];
NSArray *proteinArray = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"Proteins"];
childController.protein = [proteinArray objectAtIndex:indexPath.row];
NSArray *carbohydratesArray = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"Carbohydrates"];
childController.carbohydrates = [carbohydratesArray objectAtIndex:indexPath.row];
NSArray *fatArray = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"Fat"];
childController.fat = [fatArray objectAtIndex:indexPath.row];
NSArray *caloriesArray = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"Calories"];
childController.calories = [caloriesArray objectAtIndex:indexPath.row];
NSArray *textFieldArray = [[dictionary objectForKey:#"Products"]valueForKeyPath:#"TextField"];
childController.myBool = [textFieldArray objectAtIndex:indexPath.row];
}
[self.navigationController pushViewController:childController
animated:YES];
}
#end
In your code every time you change the text in the search bar the searchTableView function is run. You will want to make sure this function is as quick as possible.
I see you are iterating over the list of NSDictionarys from the plist file in the function and building a search array. If the plist is large this is probably quite expensive of an operation to be doing on every text change.
for (NSDictionary *dictionary in listOfItems)
{
NSArray *array = [dictionary objectForKey:#"Products"];
[searchArray addObjectsFromArray:array];
}
I think if you moved this iteration to viewDidLoad and made searchArray a global variable you will notice some speed increases.
Hope this helps.
I think you should use SqliteDatabase to store so much data,and use SQL to search your data.Every time you touch search bar,all of your data alloc in a new NSMutableArray with the method
-(void)searchTableView
this is why when you touch the search bar , it will delay 0.6sec when your data is too much

how to search in table view in iphone

hi friend i get here some problem please me i want search string in table view by searchbar i create all function of searchbar then i call in viewdidload method but it not working why
i am creating NSMutableArray *tabledata;
i am passing all value of app.journeylist in tabledata but it not wotking and application will be crash this is my controller class
//
// TJourneylistController.m
// Journey
//
// Created by rocky on 3/17/11.
// Copyright 2011 __MyCompanyName__. All rights reserved.
//
#import "TJourneylistController.h"
#import "TAddNewJourney.h"
#import "TJourneyListCell.h"
#import "JourneyAppDelegate.h"
#import "TJourneyTabBar.h"
#import "global.h"
#import "TPastJourneyTabBar.h"
#import "NewJourney.h"
#import "TStartnewjourney.h"
#import "TMapViewController.h"
#import "TShareController.h"
#import "TSpeedometerController.h"
#import "TReviewsController.h"
#define DATABASE_NAME #"journey"
#implementation TJourneylistController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
//self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(add_clicked:)];
app = (JourneyAppDelegate *)[[UIApplication sharedApplication]delegate];
sBar =[[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 30)];
sBar.delegate=self;
[self.view addSubview:sBar];
searcheddata =[[NSMutableArray alloc]init];
tabledata =[[NSMutableArray alloc]init];
[tabledata addObject:app.journeyList];
app.journeyList=[[NSMutableArray alloc]init];
for(char c = 'A';c<='Z';c++)
[app.journeyList addObject:[NSString stringWithFormat:#"%cTestString",c]]; //list = [app.journeyList retain];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 100.0;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tabledata count];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
TJourneyListCell *cell =(TJourneyListCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[TJourneyListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
NSLog(#"%#",cell);
}
NewJourney *newjoruneobject = [app.journeyList objectAtIndex:indexPath.row];
switch (indexPath.section) {
case 0:
cell.namelbl.text = newjoruneobject.journeyname;
cell.distancelbl.text = newjoruneobject.journeylocation;
cell.infolbl.text = newjoruneobject.journeydescription;
cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
break;
case 1:
cell.namelbl.text = #"Hello";
break;
default:
break;
}
return cell;
}
#pragma mark UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
// only show the status bar’s cancel button while in edit mode
sBar.showsCancelButton = YES;
sBar.autocorrectionType = UITextAutocorrectionTypeNo;
// flush the previous search content
[tabledata removeAllObjects];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
sBar.showsCancelButton = NO;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
[tabledata removeAllObjects];// remove all data that belongs to previous search
if([searchText isEqualToString:#""]|| searchText==nil){
[myTableView reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in app.journeyList)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init];
NSRange r = [name rangeOfString:searchText];
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];
}
[myTableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{ // if a valid search was entered but the user wanted to cancel, bring back the main list content
[tabledata removeAllObjects];
[tabledata addObjectsFromArray:app.journeyList];
#try
{
[myTableView reloadData];
}
#catch(NSException *e)
{
}
[sBar resignFirstResponder];
sBar.text = #"";
}
// called when Search (in our case “Done”) button pressed
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
#pragma mark -
#pragma mark Table view delegate
- (void)dealloc {
[super dealloc];
//[self.tableView release];
[mLable1 release];
//[mLable2 release];
//[mLable3 release];
//[mLable4 release];
}
#end
Write this code into your .h file:
UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource
IBOutlet UISearchBar *sbArray;
IBOutlet UITableView *tvData;
Write this code into your .m file:
- (void)viewDidLoad
{
journeyList = [[NSMutableArray alloc] init];
FinalList = [[NSMutableArray alloc] init];
for(char c = 'A';c<='Z';c++)
[journeyList addObject:[NSString stringWithFormat:#"%cTestString",c]];
for(char c = 'A';c<='Z';c++)
[FinalList addObject:[NSString stringWithFormat:#"%cTestString",c]];
[tvData reloadData];
[super viewDidLoad];
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [FinalList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"anyCell"];
if(cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"anyCell"] autorelease];
}
cell.textLabel.text = [FinalList objectAtIndex:indexPath.row];
return cell;
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)search
{
[search resignFirstResponder];
}
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
[searchBar resignFirstResponder];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
FinalList = [[NSMutableArray alloc] init];
if([sbArray.text isEqualToString:#""]|| searchText == nil)
{
[tvData reloadData];
return;
}
NSInteger counter = 0;
for(NSString *name in journeyList)
{
NSRange r = [name rangeOfString:sbArray.text];
if(r.location != NSNotFound)
{
if(r.location== 0)//that is we are checking only the start of the names.
{
[FinalList addObject:name];
}
}
counter++;
}
NSLog(#"Counter :- '%d'",[FinalList count]);
[tvData reloadData];
}

iPhone TableView Search XML

I have a question about adding XML to the searchbar in a tableview. I can get all the external XML file to load in the tableview, but when I hit the searchbar up top, and hit a letter, it crashes.
I think it's something really simple that I'm doing wrong. In my RootViewController, there's a function called searchTableView. I feel like that's where it's not picking up the search items. I think it's somewhere around the objectForKey:#"title". When I debug, I get this error message also: "NSCFArray objectForKey unrecognized selector". Here's my searchTableView function:
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSArray *array = [dictionary objectForKey:#"title"];
[searchArray addObjectsFromArray:array];
}
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
Ok figured it out. For some reason this was really hard to find documentation how to do this.
Here's my RootViewController.m below.
My pList is configured as:
Root (Array)
Item0 (Dictionary)
Name (String)
Item1 (Dictionary)
Name (String)..
Here's my code, hopefully this helps anyone else looking for help on this:
#implementation RootViewController
#synthesize listOfItems, copyListOfItems;
- (void)viewDidLoad {
[super viewDidLoad];
//Initialize the array.
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"plistArray" ofType:#"plist"];
NSMutableArray* tmpArray = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
self.listOfItems = tmpArray;
[tmpArray release];
//Initialize the copy array.
copyListOfItems = [[NSMutableArray alloc] init];
//Set the title
self.navigationItem.title = #"Search";
//Add the search bar
self.tableView.tableHeaderView = searchBar;
searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
searching = NO;
letUserSelectRow = YES;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
// Release anything that's not essential, such as cached data
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
if (searching)
return 1;
else
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (searching)
return [copyListOfItems count];
else {
//Number of rows it should expect should be based on the section
return [listOfItems count];
}
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//Get the selected country
NSString *selectedCountry = nil;
if(searching)
selectedCountry = [copyListOfItems objectAtIndex:indexPath.row];
else {
// Navigation logic may go here. Create and push another view controller.
}
NSDictionary *dictionary = [self.listOfItems objectAtIndex:indexPath.row];
FoodDetail *dvController = [[FoodDetail alloc] initWithNibName:#"FoodDetail" bundle:nil andDictionary: dictionary];
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:dvController animated:YES];
[dvController release];
}
// 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] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
// Set up the cell...
if(searching)
cell.textLabel.text = [copyListOfItems objectAtIndex:indexPath.row];
else {
cell.textLabel.text = [[self.listOfItems objectAtIndex:indexPath.row]
objectForKey:#"Name"];
}
return cell;
}
- (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if(letUserSelectRow)
return indexPath;
else
return nil;
}
#pragma mark -
#pragma mark Search Bar
- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar {
//This method is called again when the user clicks back from the detail view.
//So the overlay is displayed on the results, which is something we do not want to happen.
if(searching)
return;
//Add the overlay view.
if(ovController == nil)
ovController = [[OverlayViewController alloc] initWithNibName:#"OverlayView" bundle:[NSBundle mainBundle]];
CGFloat yaxis = self.navigationController.navigationBar.frame.size.height;
CGFloat width = self.view.frame.size.width;
CGFloat height = self.view.frame.size.height;
//Parameters x = origion on x-axis, y = origon on y-axis.
CGRect frame = CGRectMake(0, yaxis, width, height);
ovController.view.frame = frame;
ovController.view.backgroundColor = [UIColor grayColor];
ovController.view.alpha = 0.5;
ovController.rvController = self;
[self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
searching = YES;
letUserSelectRow = NO;
self.tableView.scrollEnabled = NO;
//Add the done button.
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemDone
target:self action:#selector(doneSearching_Clicked:)] autorelease];
}
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
//Remove all objects first.
[copyListOfItems removeAllObjects];
if([searchText length] > 0) {
[ovController.view removeFromSuperview];
searching = YES;
letUserSelectRow = YES;
self.tableView.scrollEnabled = YES;
[self searchTableView];
}
else {
[self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view];
searching = NO;
letUserSelectRow = NO;
self.tableView.scrollEnabled = NO;
}
[self.tableView reloadData];
}
- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar {
[self searchTableView];
}
- (void) searchTableView {
NSString *searchText = searchBar.text;
NSMutableArray *searchArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in listOfItems)
{
NSString *text1 = [dictionary objectForKey:#"Name"];
[searchArray addObject:text1];
}
NSLog(#"%s: searchArray=%#", __func__, searchArray);
for (NSString *sTemp in searchArray)
{
NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (titleResultsRange.length > 0)
[copyListOfItems addObject:sTemp];
}
[searchArray release];
searchArray = nil;
}
- (void) doneSearching_Clicked:(id)sender {
searchBar.text = #"";
[searchBar resignFirstResponder];
letUserSelectRow = YES;
searching = NO;
self.navigationItem.rightBarButtonItem = nil;
self.tableView.scrollEnabled = YES;
[ovController.view removeFromSuperview];
[ovController release];
ovController = nil;
[self.tableView reloadData];
}
- (void)dealloc {
[ovController release];
[copyListOfItems release];
[searchBar release];
[listOfItems release];
[super dealloc];
}
#end