I’m a little stumped, for some reason the following code causes my app to crash on a real iPhone although it runs fine in the simulator, all it does it grabs some json and puts it in a list view, does anyone have any idea why it keeps crashing? Any help is greatly appreciated!
——–SecondViewController.m——
#import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self fetchPrices];
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)fetchPrices
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: @"http://url.php"]];
NSError* error;
prices = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return prices.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"PriceCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *price = [prices objectAtIndex:indexPath.row];
NSString *text = [price objectForKey:@"name"];
NSString *name = [price objectForKey:@"price"];
cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:@"Price: %@", name];
return cell;
}
@end
—–SecondViewController.h—-
#import <UIKit/UIKit.h>
@interface SecondViewController : UITableViewController {
NSArray *prices;
}
- (void)fetchPrices;
@end
—- Crash Log —-
http://pastebin.com/cnf6L7Jf
Problem is that NSArray *prices is at random value between the time your fetching the price and when you’re dealing with the value. Secondly you’re not retaining it. So prices can be garbage value too.
The cleaner way is to
so that “prices” is nil when you’re initialing your tablecontroller, and always available when u need it.
Don’t forget to release it in your dealloc method