Need Help Adding User's Text To NSArray - iphone

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

Related

Error when implementing MWFeedParser

I trying to use the MWFeedParser library. I think the problem is that I want to use a view controller with a table view to display the news. Now there comes nothing up in my table view when launching the app. The code for the news view controller looks like this:
.H:
#import "MWFeedItem.h"
#import "MWFeedParser.h"
#interface NewsViewController : UIViewController <MWFeedParserDelegate> {
IBOutlet UILabel *label;
// Parsing
MWFeedParser *feedParser;
NSMutableArray *parsedItems;
// Displaying
NSArray *itemsToDisplay;
NSDateFormatter *formatter;
IBOutlet UITableView *tableView;
}
// Properties
#property (nonatomic, retain) NSArray *itemsToDisplay;
#property (nonatomic, retain) IBOutlet UITableView *tableView;
#end
.M:
#import "NSString+HTML.h"
#import "MWFeedParser.h"
#import "DetailTableViewController.h"
#implementation NewsViewController
#synthesize itemsToDisplay, tableView;
#pragma mark -
#pragma mark View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"News", #"News");
self.tabBarItem.image = [UIImage imageNamed:#"icon_news"]; }
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Date
// Setup
self.title = #"News";
formatter = [[NSDateFormatter alloc] init];
[formatter setDateStyle:NSDateFormatterShortStyle];
[formatter setTimeStyle:NSDateFormatterShortStyle];
parsedItems = [[NSMutableArray alloc] init];
self.itemsToDisplay = [NSArray array];
// Refresh button
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refresh)];
// Parse
NSURL *feedURL = [NSURL URLWithString:#"http://www.website.com/feed/"];
feedParser = [[MWFeedParser alloc] initWithFeedURL:feedURL];
feedParser.delegate = self;
feedParser.feedParseType = ParseTypeFull; // Parse feed info and all items
feedParser.connectionType = ConnectionTypeAsynchronously;
[feedParser parse];
UIImage *someImage = [UIImage imageNamed:#"back_active1#2x.png"];
[button setBackgroundImage:someImage forState:UIControlStateHighlighted];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)viewDidAppear:(BOOL)animated {
static BOOL first = YES;
if (first) {
UIViewController *popup = [[Home1ViewController alloc] initWithNibName:#"Home1ViewController" bundle:nil];
[self presentViewController:popup animated:NO completion:nil];
first = NO;
}
}
#pragma mark -
#pragma mark Parsing
// Reset and reparse
- (void)refresh {
self.title = #"Refreshing...";
[parsedItems removeAllObjects];
[feedParser stopParsing];
[feedParser parse];
/*
self.tableView.userInteractionEnabled = NO;
self.tableView.alpha = 0.3;
*/
}
- (void)updateTableWithParsedItems {
self.itemsToDisplay = [parsedItems sortedArrayUsingDescriptors:
[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:#"date"
ascending:NO]]];
/* self.tableView.userInteractionEnabled = YES;
self.tableView.alpha = 1;
[self.tableView reloadData];
*/
}
#pragma mark -
#pragma mark MWFeedParserDelegate
- (void)feedParserDidStart:(MWFeedParser *)parser {
NSLog(#"Started Parsing: %#", parser.url);
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedInfo:(MWFeedInfo *)info {
NSLog(#"Parsed Feed Info: “%#”", info.title);
self.title = info.title;
}
- (void)feedParser:(MWFeedParser *)parser didParseFeedItem:(MWFeedItem *)item {
NSLog(#"Parsed Feed Item: “%#”", item.title);
if (item) [parsedItems addObject:item];
}
- (void)feedParserDidFinish:(MWFeedParser *)parser {
NSLog(#"Finished Parsing%#", (parser.stopped ? #" (Stopped)" : #""));
[self updateTableWithParsedItems];
}
- (void)feedParser:(MWFeedParser *)parser didFailWithError:(NSError *)error {
NSLog(#"Finished Parsing With Error: %#", error);
if (parsedItems.count == 0) {
self.title = #"Failed"; // Show failed message in title
} else {
// Failed but some items parsed, so show and inform of error
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Parsing Incomplete"
message:#"There was an error during the parsing of this feed. Not all of the feed items could parsed."
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
[self updateTableWithParsedItems];
}
#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 itemsToDisplay.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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
// Configure the cell.
MWFeedItem *item = [itemsToDisplay objectAtIndex:indexPath.row];
if (item) {
// Process
NSString *itemTitle = item.title ? [item.title stringByConvertingHTMLToPlainText] : #"[No Title]";
NSString *itemSummary = item.summary ? [item.summary stringByConvertingHTMLToPlainText] : #"[No Summary]";
// Set
cell.textLabel.font = [UIFont boldSystemFontOfSize:15];
cell.textLabel.text = itemTitle;
NSMutableString *subtitle = [NSMutableString string];
if (item.date) [subtitle appendFormat:#"%#: ", [formatter stringFromDate:item.date]];
[subtitle appendString:itemSummary];
cell.detailTextLabel.text = subtitle;
}
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Show detail
DetailTableViewController *detail = [[DetailTableViewController alloc] initWithStyle:UITableViewStyleGrouped];
detail.item = (MWFeedItem *)[itemsToDisplay objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detail animated:YES];
// Deselect
[self->tableView deselectRowAtIndexPath:indexPath animated:YES];
}
#end
In IB, I've dragged a table view onto the view and linked it to dataSource and delegate. But nothing shows up in the table view.
Would really appreciate some answers/ideas!
Thanks.
i think you should uncomment the following line in your "updateTableWithParsedItems" method:
[self.tableView reloadData];

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

UISearchBar Crash When Start Typing

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!!

Can't extracts information from RSS - Xcode

I built an app, and i left the Rss for the end, when i built it, everything works, except i can't see the information from the rss, i can see the title in the table view, but i can't see the image, Title, and description.
Please help me with this,
Thank From advance,
John
(The Application is based on : View Based Application !)
also, i attach my code :
-(void)reloadRss{
[self toggleToolBarButtons:NO];
[[self rssParser]startProcess];
}
-(void)toggleToolBarButtons:(BOOL)newState{
NSArray *toolbarItems = self.toolbar.items;
for (UIBarButtonItem *item in toolbarItems){
item.enabled = newState;
}
}
//Delegate method for blog parser will get fired when the process is completed
- (void)processCompleted{
//reload the table view
[self toggleToolBarButtons:YES];
[[self tableView]reloadData];
}
-(void)processHasErrors{
//Might be due to Internet
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"The" message:#"איןאפשרות להוריד מידע. אנאבדוק את חיבור האינטרנט שלך." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
[self toggleToolBarButtons:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[self rssParser]rssItems]count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"rssItemCell"];
if(nil == cell){
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"rssItemCell"]autorelease];
}
cell.textLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]title];
cell.detailTextLabel.text = [[[[self rssParser]rssItems]objectAtIndex:indexPath.row]description];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[[self viewController] setCurrentlySelectedBlogItem:[[[self rssParser]rssItems]objectAtIndex:indexPath.row]];
[self.view addSubview:newsr];
}
-(IBAction)rss{
[self.view addSubview:rss];
}
- (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); }
-(void)openWebLink{ // open a dialog with an OK and cancel button
UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:#"האם אתה רוצה לפתוח דף זה ב-Safari ?" delegate:self cancelButtonTitle:#"בטל" destructiveButtonTitle:#"אשר" otherButtonTitles:nil];
actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
[actionSheet showFromToolbar:_toolbar];
[actionSheet release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
if(buttonIndex == 0){
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[[self viewController] currentlySelectedBlogItem]linkUrl]]];
}
}
- (void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
NSString * mediaUrl = [[[self viewController]currentlySelectedBlogItem]mediaUrl];
[[self image]setImage:[UIImage imageNamed:#"unknown.jpg"]];
if(nil != mediaUrl){
NSData* imageData;
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
#try {
imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:mediaUrl]];
}
#catch (NSException * e) {
//Some error while downloading data
}
#finally {
UIImage * imageFromImageData = [[UIImage alloc] initWithData:imageData];
[[self image]setImage:imageFromImageData];
[imageData release];
[imageFromImageData release];
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
self.titleTextView.text = [[[self viewController] currentlySelectedBlogItem]title];
self.descriptionTextView.text = [[[self viewController] currentlySelectedBlogItem]description];
}
#end
Try to decode the content of the RSS with something like:
NSWindowsCP1252StringEncoding
NSUTF8StringEncoding
...

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