【发布时间】:2012-08-18 16:02:19
【问题描述】:
我正在开发一个将 JSON 数据带入 TableView 的应用程序。但在 JSON 操作的代码启动的那一刻,应用程序崩溃并出现 SIGABRT 错误。下面是我正在使用的代码(当然,出于安全原因减去实际 URL):
// START - CONNECT TO JSON FILE ON SERVER AND DOWNLOAD INFORMATION
- (void)fetchTags
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:
[NSURL URLWithString: @"URL goes here..."]];
NSError* error;
//tags = how many objects there are in the JSON file containing data
tags = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSDictionary *tagz = [NSJSONSerialization JSONObjectWithData:data 选项:kNilOptions 错误:&error];
tags = [tagz objectForKey:@"name"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});
}
// END - CONNECT TO JSON FILE ON SERVER AND DOWNLOAD INFORMATION
//START - NUMBER OF ROWS TO GENERATE
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tags.count;
}
//END - NUMBER OF ROWS TO GENERATE
// START - PULL IN INFORMATION FROM JSON AND DISPLAY IN CELLS
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"TagCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *tag = [tags objectAtIndex:indexPath.row];
NSString *name = [tag objectForKey:@"name"];
if ([tag objectForKey:@"name"] != NULL)
cell.textLabel.text = name;
return cell;
}
// END - PULL IN INFORMATION FROM JSON AND DISPLAY IN CELLS
以下是 URL 指向的 JSON 数据: {“sessionid”:“0.97880095305420120818085118”,“option2”:“”,“logonresult”:“ACCEPT”,“projects”:[{“projid”:2012011101,“name”:“\u5909\u66f4\u5c65\u6b74\ u30c6\u30b9\u30c8"}, {"projid": 2011101401, "name": "20111014-01"}, {"projid": 201111001, "name": "\u5c3e\u7530\u90b8\u30ea\u30d5\u30a9 \u30fc\u30e0" }], "option1": ""}
这是崩溃时返回的完整错误: 2012-08-19 00:32:59.421 CameraTest[2141:707]-[__NSCFDictionary objectAtIndex:]:无法识别的选择器发送到实例 0x16f750 2012-08-19 00:32:59.423 CameraTest[2141:707] * 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[__NSCFDictionary objectAtIndex:]:无法识别的选择器发送到实例 0x16f750 '
谁能发现我做错了什么或推荐我参考可能有帮助的教程?
提前致谢!
编辑:放置在 (void)fetchTags 中的以下代码修复了崩溃,但我仍然遇到问题,因为数据没有被拉入我的单元格:
NSDictionary *tagz = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
tags = [tagz objectForKey:@"name"];
【问题讨论】:
-
NSString *name = [tag objectForKey:@"name"]; { if ([tag objectForKey:@"name"] != NULL) cell.textLabel.text = name; return cell; }}第一个大括号是干什么用的? (就在 if 条件之前) -
感谢您发现这一点,我刚刚编辑了我的代码,删除了第一个大括号和相应的右括号。但仍然出现同样的错误。
-
JSONObjectWithData: 返回一个 NSArray 吗?
-
我还建议检查是否
tags.count != 0。请发送NSLog(@"Tags Count: %d", tags.count);并进行验证。 -
tags指的是什么?