【发布时间】:2014-03-20 11:15:51
【问题描述】:
我正在尝试从我的服务器上的 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];
但我没有将这些值解析到表格视图中。我想将它们解析为 UILabel。所以我尝试的是声明新的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
【问题讨论】:
-
在第二行中,你的 alloc/init
statsHome,(与self.statsHome?)是空的,你直接尝试从中获取一个值(objectAtIndex:statsIndex),所以,那就是它崩溃是正常的。 -
那我应该怎么做呢? @Larme
-
我会等到我得到我的值(通过 JSON 请求),然后再设置标签。
-
但是我该怎么做呢? @Larme
标签: ios objective-c json parsing