【发布时间】:2014-11-12 08:48:26
【问题描述】:
我正在使用故事板构建一个 iOS 文章阅读应用程序。我正在使用 AFNetworking 库来解析表格视图中的 json。
我面临一个问题,即更新的文章未显示在表格视图中,这意味着如果在 json 中添加了新文章但未在我的表格视图中更新。
这是我的代码:
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView reloadData];
x=2;
tempJson = [[NSMutableArray alloc] init];
[self.tableView reloadData];
NSString *jsonLink=[NSString stringWithFormat:@"http://cccccc.com/json.php?token=hashg156349&page=1"];
NSURL *url = [[NSURL alloc] initWithString:jsonLink];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30.0];
[request setTimeoutInterval:120];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSArray *jsonArray = (NSArray *)responseObject;
dispatch_async(dispatch_get_main_queue(), ^{
for (NSDictionary *dic in jsonArray) {
Json *json = [[Json alloc] initWithDictionary:dic];
[tempJson addObject:json];
}
self.jsons = [[NSArray alloc] initWithArray:tempJson];
// tempNinjas = nil;
[self.tableView reloadData];
self.tableView.separatorColor = [UIColor colorWithRed:190/255.0 green:190/255.0 blue:190/255.0 alpha:1.0];
});
});
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
message:[error localizedDescription]
delegate:nil
cancelButtonTitle:@"Ok"
otherButtonTitles:nil];
[alertView show];
}];
[operation start];
}
【问题讨论】:
-
你能告诉我们你的 TableViewDataSource 方法吗?
-
此代码仅在创建此视图时运行一次 (viewDidLoad),您可能希望在每次显示视图时更新数据 (viewDidAppear),或者如果用户可以刷新数据,则更频繁地更新数据下拉刷新操作
-
感谢@dirgroten 是的,我想在每次显示视图时更新数据。
-
每次点击 tableview 时最好在 viewWillAppear 中使用此代码重新加载或将此代码留在 ViewDidLoad 和 viewWillAppear 下使用 [self.tableView reloadData];
-
@ShashankBohra 这不能解决您的问题。好像数据源没有设置为self.json数组。
标签: ios objective-c json uitableview afnetworking