I'm just learning iphone development, so please forgive me for what is probably a beginner error. I've searched around and haven't found anything specific to my problem, so hopefully it is an easy fix.
The book has examples of building a table from data hard coded via an array. Unfortunately it never really tells you how to get data from a URL, so I've had to look that up and that is where my problems show up.
When I debug in xcode, it seems like the count is correct, so I don't understand why it is going out of bounds?
This is the error message:
2010-05-03 12:50:42.705 Simple Table[3310:20b] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFArray objectAtIndex:]: index (1) beyond bounds (0)'
My URL returns the following string:
first,second,third,fourth
And here is the iphone code with the book's working example commented out
#import "Simple_TableViewController.h"
@implementation Simple_TableViewController
@synthesize listData;
- (void)viewDidLoad
{
/*
//working code from book
NSArray *array = [[NSArray alloc] initWithObjects:@"Sleepy", @"Sneezy", @"Bashful", @"Bashful", @"Happy",
@"Doc", @"Grumpy", @"Thorin", @"Dorin", @"Norin", @"Ori", @"Balin", @"Dwalin", @"Fili", @"Kili", @"Oin",
@"Gloin", @"Bifur", @"Bofur", @"Bombur", nil];
self.listData = array;
[array release];
*/
//code from interwebz that crashes
NSString *urlstr = [[NSString alloc] initWithFormat:@"http://www.mysite.com/folder/iphone-test.php"];
NSURL *url = [[NSURL alloc] initWithString:urlstr];
NSString *ans = [NSString stringWithContentsOfURL:url];
NSArray *listItems = [ans componentsSeparatedByString:@","];
self.listData = listItems;
[urlstr release];
[url release];
[ans release];
[listItems release];
[super viewDidLoad];
}
- (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 any retained subviews of the main view.
// e.g. self.myOutlet = nil;
self.listData = nil;
[super viewDidUnload];
}
- (void)dealloc
{
[listData release];
[super dealloc];
}
#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.listData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *SimpleTableIdentifier = @"SimpleTableIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:SimpleTableIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SimpleTableIdentifier] autorelease];
}
NSUInteger row = [indexPath row];
cell.textLabel.text = [listData objectAtIndex:row];
return cell;
}
@end