UISearchBar Crash When Start Typing - iphone

I have a UISearchBar and whenever I begin typing in it I get the following crash report
[__NSCFDictionary rangeOfString:options:]: unrecognized selector sent to instance 0x6a9d210
2012-07-10 14:46:52.956 MinePedia[275:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary rangeOfString:options:]: unrecognized selector sent to instance 0x6a9d210'
* First throw call stack:
(0x11f9052 0x15d5d0a 0x11faced 0x115ff00 0x115fce2 0xaad2 0x4754b2 0x11faec9 0x242515 0x2e872f 0x2e7e1e 0x2f4ce9 0x30112a 0xbf3a39 0x11c4885 0x11c47a8 0xb381aa 0x40a88e7 0x34b3917 0x3877111 0x387a4e1 0x408385b 0x40862e3 0x4086440 0x408301d 0x3869df0 0x3869ee3 0x4087119 0x388284d 0x3882b32 0x3896e12 0x3dfc0f7 0x3895245 0x38941f2 0x38948fb 0x3dfbca4 0x38a964e 0x38970a0 0x3879a0a 0x34e4ad9 0x11fae72 0x40a35bc 0x350b7f9 0x350d87f 0x3dfe03 0x3a3792 0x3a4944 0x3a36b6 0x3acf09 0x24e406 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x32c14a 0x24e460 0x24e0c5 0x24e1f8 0x241aa9 0x2172fa9 0x11cd1c5 0x1132022 0x113090a 0x112fdb4 0x112fccb 0x2171879 0x217193e 0x23fa9b 0x22f8 0x2255)
terminate called throwing an exceptionCurrent language: auto; currently objective-c
(gdb)
My SearchTableViewController.h file:
#import <UIKit/UIKit.h>
#interface SearchTableViewController : UITableViewController <UISearchBarDelegate> {
NSMutableArray *serversArray;
NSMutableArray *modsArray;
NSMutableArray *pluginsArray;
NSMutableArray *allItemsArray;
NSMutableArray *displayItemsArray;
IBOutlet UISearchBar *theSearchBar;
}
#end
and My SearchTableViewController.m file:
#import "SearchTableViewController.h"
#implementation SearchTableViewController
- (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];
modsArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://21zach2.webs.com/iPhone/MinePedia/Plists/TopRated/Mods.plist"]];
serversArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://21zach2.webs.com/iPhone/MinePedia/Plists/TopRated/Servers.plist"]];
pluginsArray = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://21zach2.webs.com/iPhone/MinePedia/Plists/TopRated/Plugins.plist"]];
allItemsArray = [[NSMutableArray alloc] init];
displayItemsArray = [[NSMutableArray alloc] init];
[allItemsArray addObjectsFromArray:modsArray];
[allItemsArray addObjectsFromArray:serversArray];
[allItemsArray addObjectsFromArray:pluginsArray];
[displayItemsArray addObjectsFromArray:allItemsArray];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
if ([searchText length] == 0) {
[displayItemsArray removeAllObjects];
[displayItemsArray addObjectsFromArray:allItemsArray];
} else {
[displayItemsArray removeAllObjects];
for (NSString *string in allItemsArray) {
NSRange range = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[displayItemsArray addObject:string];
}
}
}
[self.tableView reloadData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
[searchBar resignFirstResponder];
[theSearchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
[theSearchBar resignFirstResponder];
[searchBar resignFirstResponder];
}
- (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;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [displayItemsArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
cell.textLabel.text = [[displayItemsArray objectAtIndex:indexPath.row] objectForKey:#"name"];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
I am using storyboard. I cant upload pictures due to lack of reputation so I cant show you what my variables are linked to.

Your allItemsArray contains dictionaries, not strings. You need to get the string value out that you want to search for, for example, if it was the string stored under the key "name":
for (NSDictionary *item in allItemsArray) {
NSString *string = [item objectForKey:#"name"];
NSRange range = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[displayItemsArray addObject:item];
}
}

for (int count = 0; count < [allItemsArray count]; count ++) {
for (NSDictionary *dict in [allItemsArray objectAtIndex:count]) {
NSString *string = [dict objectForKey:#"keyValue"];
NSRange range = [string rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[displayItemsArray addObject:string];
}
}
}
I hope this solves it!!

Related

how can i show accessary checked cell values in alertbox [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
how to get accessarychecked cell value and show it on alertview
how-to-get-accessarychecked-cell-value-and-show-it-on-alertview
I have created UITableView and cell in UITableView are accessarychecked . I have implemented an action named
-(IBAction) checkBoxClicked.
What I need is that I wanted to show accessarychecked cell values in Alertbox when I click on button this is the code which I have written:
#import "ViewController.h"
#implementation ViewController
#synthesize cell;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 7;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
cell= [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil)
{
cell = [[ UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [myarray objectAtIndex:indexPath.row];
/*
NSString *imagefile = [[NSBundle mainBundle] pathForResource:#"cellimage" ofType:#"png"];
UIImage *ui = [[UIImage alloc] initWithContentsOfFile:imagefile];
cell.imageView.image = ui;*/
NSString *check = [[NSBundle mainBundle] pathForResource:#"checkbox_not_ticked" ofType:#"png"];
UIImage *bi = [[UIImage alloc] initWithContentsOfFile:check];
cell.imageView.image = bi;
cell.accessoryType = UITableViewCellAccessoryNone;
return cell;
[cell release];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
} else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
-(IBAction) checkBoxClicked
{
NSArray *array = [[NSArray alloc] initWithArray:[myarray objectAtIndex:cell.accessoryType]:UITableViewCellAccessoryCheckmark];
if (array.cell.accessoryType == UITableViewCellAccessoryCheckmark)
{
UIAlertView *msg = [[ UIAlertView alloc] initWithTitle:#"selected items are given: " message:array delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil ];
[msg show ];
[msg release];
[myarray release];
}
}
//-(IBAction)checkBoxClicked{}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
myarray = [[NSArray alloc] initWithObjects:#"mondey",#"tuesday",
#"wednesday",#"thursday",#"friday",#"saturday",#"sundey", nil];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)viewDidUnload
{
[myarray release];
[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 != UIInterfaceOrientationPortraitUpsideDown);
}
#end
Use tag for each button and retrieve the button instance

getting error: expected ':' before '*' token in Xcode [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
i am trying to devlope one RSSFeed application from http://www.raywenderlich.com/2636/how-to-make-a-simple-rss-reader-iphone-app-tutorial. everything was going well till this error occurs. i have checked everything in tutorial code but couldn't find anything. i have copied the code as it is. i have stuck here & wanted to get rid off it so i can go further & work get done. i am putting the piece of code below. please anyone can help me with it.
thnx in advance..
// RootViewController.m
// RSSFun
#import "GDataXMLNode.h"
#import "GDataXMLElement-Extras.h"
#import "ASIHTTPRequest.h"
#import "RSSEntry.h"
#import "RootViewController.h"
#implementation RootViewController
#synthesize feeds = _feeds;
#synthesize queue = _queue;
#synthesize allEntries = _allEntries;
- (void)refresh {
for (NSString *feed in _feeds) {
NSURL *url = [NSURL URLWithString:feed];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[_queue addOperation:request];
}
}
- (void)addRows {
RSSEntry *entry1 = [[[RSSEntry alloc] initWithBlogTitle:#"1"
articleTitle:#"1"
articleUrl:#"1"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry2 = [[[RSSEntry alloc] initWithBlogTitle:#"2"
articleTitle:#"2"
articleUrl:#"2"
articleDate:[NSDate date]] autorelease];
RSSEntry *entry3 = [[[RSSEntry alloc] initWithBlogTitle:#"3"
articleTitle:#"3"
articleUrl:#"3"
articleDate:[NSDate date]] autorelease];
[_allEntries insertObject:entry1 atIndex:0];
[_allEntries insertObject:entry2 atIndex:0];
[_allEntries insertObject:entry3 atIndex:0];
}
- (void)viewDidLoad {
[super viewDidLoad];
self.title = #"Feeds";
self.allEntries = [NSMutableArray array];
self.queue = [[[NSOperationQueue alloc] init] autorelease];
self.feeds = [NSArray arrayWithObjects:#"http://feeds.feedburner.com/RayWenderlich",
#"http://feeds.feedburner.com/vmwstudios",
#"http://idtypealittlefaster.blogspot.com/feeds/posts/default",
#"http://www.71squared.com/feed/",
#"http://cocoawithlove.com/feeds/posts/default",
#"http://feeds2.feedburner.com/brandontreb",
#"http://feeds.feedburner.com/CoryWilesBlog",
#"http://geekanddad.wordpress.com/feed/",
#"http://iphonedevelopment.blogspot.com/feeds/posts/default",
#"http://karnakgames.com/wp/feed/",
#"http://kwigbo.com/rss",
#"http://shawnsbits.com/feed/",
#"http://pocketcyclone.com/feed/",
#"http://www.alexcurylo.com/blog/feed/",
#"http://feeds.feedburner.com/maniacdev",
#"http://feeds.feedburner.com/macindie",
nil];
[self refresh];
}
/*
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
*/
/*
- (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];
}
*/
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations.
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/
- (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.
}
- (void)viewDidUnload {
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}
- (void)requestFinished:(ASIHTTPRequest *)request {
//Error occurs here
[_queue addOperationWithBlock:^
{
NSError *error;
GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData]
options:0 error:&error];
if (doc == nil) {
NSLog(#"Failed to parse %#", request.url);
} else {
NSMutableArray *entries = [NSMutableArray array];
[self parseFeed:doc.rootElement entries:entries];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
for (RSSEntry *entry in entries) {
int insertIdx = 0;
[_allEntries insertObject:entry atIndex:insertIdx];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
withRowAnimation:UITableViewRowAnimationRight];
}
}];
}
}];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"Error: %#", error);
}
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
if ([rootElement.name compare:#"rss"] == NSOrderedSame) {
[self parseRss:rootElement entries:entries];
} else if ([rootElement.name compare:#"feed"] == NSOrderedSame) {
[self parseAtom:rootElement entries:entries];
} else {
NSLog(#"Unsupported root element: %#", rootElement.name);
}
}
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSArray *channels = [rootElement elementsForName:#"channel"];
for (GDataXMLElement *channel in channels) {
NSString *blogTitle = [channel valueForChild:#"title"];
NSArray *items = [channel elementsForName:#"item"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = [item valueForChild:#"link"];
NSString *articleDateString = [item valueForChild:#"pubDate"];
NSDate *articleDate = nil;
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
}
- (void)parseAtom:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
NSString *blogTitle = [rootElement valueForChild:#"title"];
NSArray *items = [rootElement elementsForName:#"entry"];
for (GDataXMLElement *item in items) {
NSString *articleTitle = [item valueForChild:#"title"];
NSString *articleUrl = nil;
NSArray *links = [item elementsForName:#"link"];
for(GDataXMLElement *link in links) {
NSString *rel = [[link attributeForName:#"rel"] stringValue];
NSString *type = [[link attributeForName:#"type"] stringValue];
if ([rel compare:#"alternate"] == NSOrderedSame &&
[type compare:#"text/html"] == NSOrderedSame) {
articleUrl = [[link attributeForName:#"href"] stringValue];
}
}
NSString *articleDateString = [item valueForChild:#"updated"];
NSDate *articleDate = nil;
RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle
articleTitle:articleTitle
articleUrl:articleUrl
articleDate:articleDate] autorelease];
[entries addObject:entry];
}
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [_allEntries 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] autorelease];
}
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setTimeStyle:NSDateFormatterMediumStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate];
cell.textLabel.text = entry.articleTitle;
cell.detailTextLabel.text = [NSString stringWithFormat:#"%# - %#", articleDateString, entry.blogTitle];
return cell;
}
/*
// Override to support row selection in the table view.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here -- for example, create and push another view controller.
// AnotherViewController *anotherViewController = [[AnotherViewController alloc] initWithNibName:#"AnotherView" bundle:nil];
// [self.navigationController pushViewController:anotherViewController animated:YES];
// [anotherViewController release];
}
*/
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source.
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)dealloc {
[super dealloc];
[_allEntries release];
_allEntries = nil;
[_queue release];
_queue = nil;
[_feeds release];
_feeds = nil;
}
#end
Just before your dealloc method you have a spurious */ which needs removing.
enter code hereRight at teh end of your file you have the following:
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
That last end comment block */ should be removed as it has no start block. leaving:
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}

Persisting Checklists on a UITableView using NSUserDefults

I have a very simple table view which shows a list of days. Once the user selects which days are relevant to them this data is saved in NSUserdefaults. I then need the check marks to remain once the user has exited then re-entered the table view.
I am very close to getting my desired functionality - I can save the array of check marked items and get it to persist using NSUserDefaults but I don't know how to make these selections persist (keep a check mark next to the selected item) once a user has exited then re-entered the table view.
I know that I need to edit the cellForRowAtIndexPath method but I am not sure exactly what to do. Any help would be greatly appreciated.
I have attached my code below:
#import "DayView.h"
#implementation DayView
#synthesize sourceArray;
#synthesize selectedArray;
- (id)init
{
self = [super initWithStyle:UITableViewStyleGrouped];
if (self) {
// Custom initialization
[[self navigationItem] setTitle:#"Days"];
[[self tableView] setBackgroundColor:[UIColor clearColor]];
}
return self;
}
- (void)viewWillDisappear:(BOOL)animated
{
// create a standardUserDefaults variable
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
// Convert array to string
NSString *time = [[selectedArray valueForKey:#"description"] componentsJoinedByString:#","];
// saving an NSString
[standardUserDefaults setObject:time forKey:#"string"];
NSLog(#"Disapear: %#", time);
}
- (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];
// create a standardUserDefaults variable
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];
// getting an NSString object
NSString *myString = [standardUserDefaults stringForKey:#"string"];
NSLog(#"Appear: %#", myString);
NSMutableArray * tempArray = [[NSMutableArray alloc] init];
[self setSelectedArray:tempArray];
[tempArray release];
NSArray * tempSource = [[NSArray alloc] initWithObjects:#"Monday", #"Tuesday", #"Wednesday", #"Thursday", #"Friday", #"Saturday",nil];
[self setSourceArray:tempSource];
[tempSource release];
[self.tableView reloadData];
}
#pragma mark -
#pragma mark Table view data source
// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.sourceArray count];;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSString *time = [sourceArray objectAtIndex:indexPath.row];
cell.textLabel.text = time;
if ([self.selectedArray containsObject:[self.sourceArray objectAtIndex:indexPath.row]])
{
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
}
else
{
[cell setAccessoryType:UITableViewCellAccessoryNone];
}
NSLog(#"Selected Days: %#", selectedArray);
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return #"Which times you are available?";
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if ([self.selectedArray containsObject:[self.sourceArray objectAtIndex:indexPath.row]]){
[self.selectedArray removeObjectAtIndex:[self.selectedArray indexOfObject: [self.sourceArray objectAtIndex:indexPath.row]]];
}
else
{
[self.selectedArray addObject:[self.sourceArray objectAtIndex:indexPath.row]];
}
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Create your tempSource as follows:
NSMutableArray * tempSource = [[NSMutableArray alloc] init];
NSArray *daysOfWeek = [NSArray arrayWithObjects:#"Monday", #"tuestay", #"wednesday", #"thursday", #"friday", #"saturday", #"sunday",nil];
for (int i = 0; i < 7; i++)
{
NSString *dayOfWeek = [daysOfWeek objectAtIndex:i];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:dayOfWeek, #"day", [NSNumber numberWithBool:NO], #"isSelected",nil];
[tempSource addObject:dict];
}
[self setSourceArray:tempSource];
[tempSource release];
Then use this Array in cellForRow and didSelect as follows:
cellForRow
NSDictionary *dayOfWeekDictionary = [sourceArray objectAtIntex:indexPath.row];
cell.textLabel.text = [dayOfWeekDictionary objectForKey:#"day"];
if ([[dayOfWeekDictionary objectForKey:#"isSelected"] boolValue])
[cell setAccessoryType:UITableViewCellAccessoryCheckmark];
else
[cell setAccessoryType:UITableViewCellAccessoryNone];
didSelect
NSDictionary *dayOfWeekDictionary = [sourceArray objectAtIntex:indexPath.row];
if ([[dayOfWeekDictionary objectForKey:#"isSelected"] boolValue])
[dayOfWeekDictionary setObject:[NSNumber numberWithBool:NO] forKey:#"isSelected"];
else
[dayOfWeekDictionary setObject:[NSNumber numberWithBool:YES] forKey:#"isSelected"];
To save this Array use this statement:
[[NSUserDefaults standardUserDefaults] setObject:sourceArray forKey:#"array"];

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];
}

Need Help Adding User's Text To NSArray

I am prompting users for text when they click the + for my table. They are shown a UIAlert with textField prompt and the text is then saved as a string in a dictionary.
I have the following code so far:
- (void)viewDidLoad
{
NSArray *myData = [NSMutableArray arrayWithContentsOfFile:#"mydata"];
if (myData == nil)
{
myData = [NSMutableArray array];
}
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
}
}
The NSlog shows the entered text but how do I get it to save in my Array?
Also, should I save the text as a string, a dictionary with a string in it, or an array itself with a string in it? Because there is going to be a dictionary or array within each of these other dictionaries with objects that the user can choose from (the objects they can choose from are stored in a separate plist).
For example, User types in "Arms Day" for the prompt, then it saves to the array and he can choose from all the exercises for the arm that I have stored in a data.plist
Update with new code:
#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#implementation RoutineTableViewController
#synthesize routineArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
/*
NSArray *myData = [NSMutableArray arrayWithContentsOfFile:#"mydata"];
if (myData == nil)
{
myData = [NSMutableArray array];
}
*/
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
[self.routineArray addObject:entered]; }
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// do delete
// get count of rows in UITableView and hide table if it's empty
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (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 [routineArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [self.routineArray objectAtIndex:indexPath.row];
return cell;
}
Update 3:
#implementation RoutineTableViewController
#synthesize myArray;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
myArray = [[NSMutableArray alloc] init];
myData = [[NSMutableArray arrayWithContentsOfFile:#"mydata"] retain];
if (myData == nil)
{
myData = [NSMutableArray array];
}
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
//if(myData && entered)
{
[myArray addObject:entered];
}
}
NSLog(#"%#",[myArray objectAtIndex:0]);
[tableView reloadData];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// do delete
// get count of rows in UITableView and hide table if it's empty
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (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 [myArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [self.myArray objectAtIndex:indexPath.row];
return cell;
}
Suggest you to save the user text in NSMutableArray.
Declare NSMutableArray variable in your .h file,
NSMutableArray *myData;
In Source file .m:
myData = [[NSMutableArray arrayWithContentsOfFile:#"mydata"] retain];
if (myData == nil)
{
myData = [NSMutableArray array];
}
Add text in Array.
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
if(myData && entered)
{
[myArray addObject:entered];
}
}
Neither of the current answers are very helpful, because they haven't looked at your code! Just doing addObject won't help you, in fact your code probably won't compile if you add it.
Your array is a local variable, so it's only available inside the viewDidLoad method. If you try to add anything to it inside yourwillDismissWithButtonIndex method without changing how you're declaring your array you'll cause a compiler error. The first step is to make your myData variable available to all your methods. You can use a property to achieve this - if you're unsure how to declare a property you should think about perhaps stepping back and reading up a bit more on Objective-C before diving in.
So, in your header file you might declare:
#property (nonatomic, retain) NSMutableArray *myArray;
And in your implementation file:
#synthesize myArray
- (void)viewDidLoad
{
self.myData = [NSMutableArray arrayWithContentsOfFile:#"mydata"];
....
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
[self.myArray addObject:entered];
Hope that helps you out!
Make your array as part of your class and use its reference in your method to add it to array.
[myArray addObject:entered];