将JSON解析为UILabel时出现空数组错误

时间:2014-03-20 11:15:52

标签: ios objective-c json parsing

我正在尝试从服务器上的JSON文件中解析一些文本。我正在从文件中解析三个不同的值:"value1":"some_value""value2":"some_value""value3":"some_value"

我正在声明一个名为statsHome的NSMutableArray,我在viewDidLoad方法中初始化,如下所示:statsHome = [[NSMutableArray alloc] init];

问题是我初始化数组后,我需要设置一个NSDictionary。如果我在表格视图中这样做,我会写:

NSDictionary *stats = [self.statshome objectAtIndex:indexPath.row];

但我没有将这些值解析为表视图。我想将它们解析为UILabels。所以我尝试的是宣布新的NSUInteger。因为我无法在viewDidLoad方法中使用indexPath.row。我叫它statsIndex

但是当我启动应用程序时,它会崩溃并向我显示以下错误消息:Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'

其余代码如下所示:

@interface DEMOHomeViewController () {
    NSUInteger statsIndex;
}
@end

@implementation DEMOHomeViewController
@synthesize statsHome;
@synthesize twitterFollowers;
@synthesize facebookLikes;
@synthesize instagramFollowers;

- (void)viewDidLoad
{
    [super viewDidLoad];  

    statsHome = [[NSMutableArray alloc] init];

    NSDictionary *stats = [self.statsHome objectAtIndex:statsIndex];

    value1.text = [stats objectForKey:@"value1"];
    value2.text = [stats objectForKey:@"value2"];
    value3.text = [stats objectForKey:@"value3"];

    NSURL *url1 = [[NSURL alloc] initWithString:@"the-json-file-with-the-values.php/file.json"];
    NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:url1];

    AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        self.statsHome = [[NSArray alloc] initWithArray:JSON];
        [self.activityIndicatorView stopAnimating];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation1 start];

}

@end

2 个答案:

答案 0 :(得分:1)

错误是正确的:您正在尝试在设置数据之前从数组中获取数据。你应该在下面的代码中做一些事情。

- (void)viewDidLoad
{
    [super viewDidLoad];  

    NSURL *url1 = [[NSURL alloc] initWithString:@"the-json-file-with-the-values.php/file.json"];
    NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL:url1];

    AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        [self.activityIndicatorView stopAnimating];
        [self updateDataWithJSON:JSON]; // <- Here we will update our data
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation1 start];

}

- (void)updateDataWithJSON:(id)JSON 
{
    self.statsHome = [[NSArray alloc] initWithArray:JSON];

    NSDictionary *stats = [self.statsHome objectAtIndex:statsIndex];

    value1.text = [stats objectForKey:@"value1"];
    value2.text = [stats objectForKey:@"value2"];
    value3.text = [stats objectForKey:@"value3"];
}

让我给你一个建议。看起来像你的应用程序的其他部分初始化你的statsIndex。在这种情况下,最好每次访问此数组时检查statsIndex是否适合数组长度。否则,它可能是某些情况下应用程序崩溃的原因:例如,您在其他控制器中获得了数组,并且它有10个元素。您选择最后一个元素,但在DEMOHomeViewController的viewDidLoad中重新加载请求。在这个时间数组中只有9个元素(最后一个元素已被其他人删除)。 - &GT;碰撞

答案 1 :(得分:0)

NSURL * url = [NSURL URLWithString:[NSString stringWithFormat:@“url”];

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

[request setHTTPMethod:@"GET"];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

NSString *authStr = [NSString stringWithFormat:@"%@:%@", @"usernmae", @"password"];

NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];

NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:0]];

NSLog(@"%@",authValue);//

[request setValue:authValue forHTTPHeaderField:@"Authorization"];

[request setURL:url];
NSLog(@"%@",url);

NSError *error;

NSHTTPURLResponse *response;

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSLog(@"Response code: %ld", (long)[response statusCode]);

NSLog(@"Data is %@",data);