如题。
使用AFN请求数据时,页面不显示数据,debug的时候发现dataArray数组没有值,但是调用testJson这个方法的时候,的确是请求到有数据的,并且已经将数据解析并添加到dataArray这个数组中的啊,不知道为什么到viewDidLoad这个方法中数组dataArray就是为空。不知道是我写的代码的加载顺序有问题还是项目的哪个地方需要配置下?求高手帮忙看下。。。
#import "ViewController.h"
#import "AFNetworking.h"
#import "Model.h"
#import "Cell.h"
@interface ViewController ()
@property (nonatomic, weak) UITableView *tableView;
@property (nonatomic,strong) NSMutableArray *dataArray;
@property (nonatomic,copy) NSString *url;
@end
@implementation ViewController
- (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; UITableView *tableView = [[UITableView alloc]init]; tableView.frame = CGRectMake(0, 0, 375, 667); [self.view addSubview:tableView]; self.tableView = tableView; self.tableView.delegate = self; self.tableView.dataSource = self; self.url = @"http://api.douban.com/v2/movie/top250"; self.dataArray = [[NSMutableArray alloc] init]; //注册cell [self.tableView registerNib:[UINib nibWithNibName:@"Cell" bundle:nil] forCellReuseIdentifier:@"Cell"]; [self testJSON]; }
-(void)testJSON{
//请求数据的地址
NSString *path = self.url;
//创建管理类
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//设置数据二进制,数据格式默认json
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//利用方法请求数据
[manager GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSArray *movieArray = dic[@"subjects"];
for (NSDictionary *dict in movieArray)
{
Model *model = [[Model alloc] init];
model.movieName = dict[@"title"];
model.movieYear = dict[@"year"];
model.movieImage = dict[@"images"][@"large"];
[self.dataArray addObject:model];
}
//刷新表
[_tableView reloadData];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
}
#pragma mark ---------数据源方法-------
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.dataArray.count;
}-
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
Model *model = self.dataArray[indexPath.row];
static NSString *ID = @"ID";
Cell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
if (cell == nil) {
cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];
}
cell.name.text = model.movieName;
cell.year.text = model.movieYear;return cell;
} (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end