iPhone应用程序一直在崩溃?

时间:2012-10-09 15:01:26

标签: iphone objective-c xcode

我有点难过,由于某种原因,下面的代码导致我的应用程序在真正的iPhone上崩溃,虽然它在模拟器中运行良好,所有它都抓住了一些json并将其放在列表视图中,是否有人知道为什么它会一直崩溃吗?非常感谢任何帮助!

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

----崩溃日志---- http://pastebin.com/cnf6L7Jf

1 个答案:

答案 0 :(得分:1)

问题在于,NSArray *价格在您获取价格和处理价值之间是随机值。其次你没有保留它。所以价格也可以是垃圾价值。

更清洁的方式是

@property(nonatomic, retain)NSArray *prices;
/**/
@synthetise prices;

// then 
SELF.prices = [[NSJSONSerialization JSONObjectWithData:data
                                                 options:kNilOptions
                                                   error:&error];

这样当你初始化你的tablecontroller时“price”就是nil,并且在你需要的时候总是可用。

不要忘记在你的dealloc方法中释放它