How to Connect two tables using NSDictionary? - nsdictionary

In my iphone design, there are two table views added.
One table view is for displaying the MenuList for hotels using NsDictionary(Like Veg. NonVeg, Beverages..) and the other table view is for displaying the ListItems(Like In veg, i will Have Paneer,Rotti..) . When ever a menuList cell is selected the files inside the selected list needs to to be displayed in the other table view(ListIems).
My problem is
I am confused about
I want to use NsDictionary Alone in this two table . Can anyone give me a simple code for this. i am confused and am a fresher. Thanks In advance if someone teaches me. Please help. iam using xcode5
#interface TableViewController ()
#end
#implementation TableViewController
#synthesize menuDict ;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
menuName = [NSArray arrayWithObjects:#"Veg", #"NonVeg", #"Beverages", nil];
menuId = [NSArray arrayWithObjects:#"1", #"2", #"3", nil];
self.menuDict = [NSDictionary dictionaryWithObjects:menuName
forKeys:menuId];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#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 [[self.menuDict allKeys] count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *unifiedID = #"TableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:unifiedID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:unifiedID];
}
for (id key in self.menuDict) {
NSLog(#"key: %#, value: %#", key, [self.menuDict objectForKey:key]);
}
NSString *key = [self.menuDict allKeys][indexPath.row];
NSString *menuNameString = self.menuDict[key];
NSString *menuIdString = key;
cell.textLabel.text = menuNameString;
cell.detailTextLabel.text = menuIdString;
return cell;
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if([[segue identifier] isEqualToString:#"ShowDetails"])
{
NSDictionary *vvegDict = [[NSDictionary alloc]initWithObjectsAndKeys:#"1",#"Rotti" , #"2", #"Panner", nil] ;
DetailTableViewController *tvc = segue.destinationViewController ;
tvc.vegDict =vvegDict ;
}
}
second table :
// Is this right to declare the lists here same as my first table. Please help me in this one.
#interface DetailTableViewController ()
#end
#implementation DetailTableViewController
#synthesize vegName,vegId ;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
vegName = [NSArray arrayWithObjects:#"Rotti", #"Panneer", #"Chappathi", nil];
vegId = [NSArray arrayWithObjects:#"1", #"2", #"3", nil];
self.vegDict = [NSDictionary dictionaryWithObjects:vegName
forKeys:vegId];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1 ;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[self.vegDict allKeys]count] ;
return 1 ;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *unifiedID = #"aCellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:unifiedID];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:unifiedID];
}
for (id key in self.vegDict) {
NSLog(#"key: %#, value: %#", key, [self.vegDict objectForKey:key]);
}
NSString *key = [self.vegDict allKeys][indexPath.row];
NSString *vegNameString = self.vegDict[key];
NSString *vegIdString = key;
cell.textLabel.text = vegNameString;
cell.detailTextLabel.text = vegIdString;
return cell;
}

If you are using Segues to go from one uitableviewcontroller to other then you can use
-prepareForSegue:sender:
in this method you can set an NSDictionary property in the destination view controller. You can get the the destination view controller from the the sender argument.

Related

TableView to detailTableView - one step behind

When I connect the my tableView to a detailtableView I get the the "error" that the detailtableView is one step behind. For example when clicking the 2nd cell in the mastertableView it show the 1st cell detailInformation. Hope you understand my problem.
See my .m.
#import "GuideTableViewController.h"
#import "GuideDetailTableViewController.h"
#interface GuideTableViewController (){
NSArray *guide;
}
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation GuideTableViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
//JSONmetod
- (void) loadJSON{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//code
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"https://dl.dropbox.com/u/100670549/test.json"]];
NSError *error;
if (data)
{
guide = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
for (NSDictionary *dictionary in guide){
NSLog([dictionary description]);
}
}else
{
NSLog(#"Could not load data");
}
dispatch_sync(dispatch_get_main_queue(), ^{
// code
[self.tableView reloadData];
});
});
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Anropa json
[self loadJSON];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//TableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return guide.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
NSDictionary *dict = [guide objectAtIndex:indexPath.row];
cell.textLabel.text = [dict valueForKey:#"title"];
return cell;
}
//Till detailView
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:#"showStay"]){
GuideDetailTableViewController *tvc = [segue destinationViewController];
NSIndexPath *index = sender;
NSDictionary *dict = [guide objectAtIndex:index.row];
tvc.stay = dict;
}
}
-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"showStay" sender:indexPath];
}
#end
Thanks in advance!
you used didDeselectRowAtIndexPath instead of didSelectRowAtIndexPath Delegate method, common autocomplete mistake.

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

NSArray clears after 3 times view did load

I have an NSArray that contains a couple of items. The NSArray is loaded into a uitableview from another class. when I back out of the detail view and re-enter (for the 3rd time), the NSArray is empty and the tableview is empty as well. What is happening? (I am using arc so I don't think it is a leak)
- (void)viewDidLoad {
myMatch = [[Match alloc] initWithId:1 OpponentId:13];
}
- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *askCellIdent = #"askCell";
static NSString *answerCellIdent = #"answerCell";
if (indexPath.row == 0)
{
AskCell *cell = [tv dequeueReusableCellWithIdentifier:askCellIdent];
if (cell==nil) {
cell = [[AskCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:askCellIdent];
}
cell.nameLabel.text = #"Albert asked:";
cell.questionLabel.text = [NSString stringWithFormat:#"%#", [[myMatch.chat objectAtIndex:indexPath.row] objectAtIndex:1]];
return cell;
}
if (indexPath.row == 1)
{
AnswerCell *cell = [tv dequeueReusableCellWithIdentifier:answerCellIdent];
if (cell==nil) {
cell = [[AnswerCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:answerCellIdent];
}
cell.nameLabel.text = #"Hugh answered:";
cell.answerLabel.text = [NSString stringWithFormat:#"%#", [[myMatch.chat objectAtIndex:indexPath.row] objectAtIndex:1]];
return cell;
}
}
Here is the init code of the my match class:
- (id) initWithId:(NSInteger)yourId OpponentId:(NSInteger)opId {
self = [super init];
if (self != nil) {
//set your id and opponents id to the match.
[self setUserId:yourId];
[self setUserId:opId];
JSON = #"[{\"opponentId\":\"4\",\"chat\":[[\"1\",\"Does he have a beard?\"],[\"1\",\"No.\"]]}]";
//initiate the chat array.
chat = [[NSMutableArray alloc] init ];
[self loadMatch];
}
return self;
}
and here is the chat property/synthesize
NSMutableArray *chat;
#property (nonatomic, retain) NSMutableArray *chat;
#synthesize chat;
No idea whats going on, because the slog of the array is empty too!
Declare an int varable repeatCount in appDelegate
- (void)viewDidLoad
{
[super viewDidLoad];
ypurAppDelegate *appDelegate = (yourAppDelegate *)[[UIApplication sharedApplication] elegate];
appDelegate.repeatCount++;
if(appDelegate.repeatCount %3==0)
{
[array removeAllObjects];
[tableview reloaddata];
}
}
Use self.chat = [[[NSMutableArray alloc] init ]autorelease]; to initialize your array
Instead ViewDidLoad, allocate the object in initWithCoder.
- (void)viewDidLoad
{
[super viewDidLoad];
}
-(id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if( self )
{
myMatch = [[Match alloc] initWithId:1 OpponentId:13];
}
return self;
}
I think it's a problem with the populating the NSMutableArray as only once will viewDidLoad will be called. You should insert values into array in viewWillAppear Method or initiate the match class in initWithCoder.

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

iPhone: Requesting cellforrow for rows out of bounds

What did I do wrong? I just modified the Navigation Based application code a bit to read and display a JSON string. It crashes when I scroll up the list with the message Objc_msgSend and points at this as the problem: cell.textLabel.text=[[locations objectAtIndex: storyIndex] objectForKey: #"title"];
#import "RootViewController.h"
#import "JSON.h"
#implementation RootViewController
#synthesize locations;
- (NSString *)stringWithUrl:(NSURL *)url
{
// Construct a String around the Data from the response
return [[NSString alloc] initWithContentsOfURL:url];
}
-(void)jsonLoad {
NSURL *URL = [NSURL URLWithString:#"http://bombaytokyo.com/whrru/jsonexample.html"];
NSString *jsonstring = [self stringWithUrl:URL];
NSLog(jsonstring);
locations = [jsonstring JSONValue];
[jsonstring release];
}
- (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;
[self jsonLoad];
}
- (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.
[locations release];
}
- (void)viewDidUnload {
// Release anything that can be recreated in viewDidLoad or on demand.
// e.g. self.myOutlet = nil;
}
#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 0;
return [locations 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];
}
// Configure the cell.
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSLog(#"Index Path: %i",indexPath);
//NSLog(title);
cell.textLabel.text=[[locations objectAtIndex: storyIndex] objectForKey: #"title"];
return cell;
}
- (void)dealloc {
[super dealloc];
}
#end
0 based arrays, id length is 0 the 0 - 1 = -1 this will obviously cause an exception.
[indexPath indexAtPosition: [indexPath length] - 1]
change to
[indexPath indexAtPosition: [indexPath length]]
and are you sure you dont want indexPath.row. it looks like you are just returning the length each time.
solution:
self.locations = [jsonstring JSONValue];
Thanks for all the suggestions.