网络获取的数据:
代码:
#import "SecondViewController.h"
@interface SecondViewController ()
@property NSMutableData *mutableData;
@property NSString *string;
@property NSMutableArray *courses;
@end
@implementation SecondViewController
}
(void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"%@", response);
}
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if(_mutableData == nil){
_mutableData = [[NSMutableData alloc]init];
}
[_mutableData appendData:data];
}
(void)connectionDidFinishLoading:(NSURLConnection *)connection{
_string = [[NSString alloc]initWithBytes:[_mutableData bytes] length:[_mutableData length] encoding:NSUTF8StringEncoding];
NSJSONSerialization *json_courses = [NSJSONSerialization JSONObjectWithData:_mutableData options:0 error:nil];
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:_mutableData options:0 error:nil];
_courses = [[NSMutableArray alloc] init];
for(int i = 0; i < [json count]; i++){
NSString *tag = @"course";
NSString *str_i = [[NSString alloc]initWithFormat:@"%i",i];
tag = [tag stringByAppendingString:str_i];
NSJSONSerialization *json_course = [json_courses valueForKey:tag];
NSString *name = [json_course valueForKey:@"courseName"];
NSLog(@"%@",name);
[_courses addObject:name];
}
NSLog(@"%@",_courses);
//获取NSMuTableArray中第n个元素的值
//NSLog(@"%@", [_courses objectAtIndex:1]);
_mutableData = nil;
}
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(@"Array count is %i",[_courses count]);
return [_courses count];
}
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"courses" forIndexPath:indexPath];
cell.textLabel.text = [_courses objectAtIndex:[indexPath row]];
// Configure the cell...
return cell;
}
/*
// Override to support conditional editing of the table view.
/*
// Override to support editing the table view.
/*
// Override to support rearranging the table view.
/*
// Override to support conditional rearranging of the table view.
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
@end
个人分析是:该类先创建了tableview然后才获取网络数据源,可是不知道怎么解决
问题已经自行解决,原因如下:
由于获取网络数据并不在主线程中进行,所以程序会先执行后面的代码,最终导致程序虽然获得了数据源,却没有在tableview中显示出来。
此时只需要在connectionDidFinishLoading方法的末尾增加一句“[self.tableView reloadData];”来重载数据即可!