我有一个实例变量数组:
@interface ChannelsVC ()
{
NSArray *arrayofFrequencies;
}
}
@end
@implementation ChannelsVC
......
在'viewDidLoad'
中进行了分配arrayofFrequencies=[[NSArray alloc]init];
然后,我将数据从JSON数据源插入数组:
-(void)GetFrequencies{
NSString *urla=@"http://xxxxxxxx";
NSString *uria = [urla stringByAppendingString:self.lien_satellite];
NSURL *urlFrequencies= [ NSURL URLWithString:uria];
NSLog(@"Frequencies URI: %@",uria); //correct URI
NSURLRequest *request = [NSURLRequest requestWithURL:urlFrequencies];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
arrayofFrequencies=[JSON valueForKeyPath:@"frequency"];
NSLog(@"Frequencies count: %lu", (unsigned long)[arrayofFrequencies count]);//the count here is correct, I have data in the array
} failure:nil];
[operation start];
}
问题是当想要使UITableView的部分数量为'[arrayofFrequencies count];'时,它总是返回'0'!它是一个实例变量,它在'GetFrequencies'函数之外返回零。
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
NSLog(@"number of sections %ld",(long)[arrayofFrequencies count]); // always returns 0
return [arrayofFrequencies count];
}
我做错了吗?
感谢您的帮助。
控制台输出:
013-06-25 12:58:00.163 Frequencies[840:c07] number of sections 0
2013-06-25 12:58:00.165 Frequencies[840:c07] number of sections 0
2013-06-25 12:58:00.641 Frequencies[840:c07] Frequencies count: 4
答案 0 :(得分:2)
在
之后调用[tableView reloadData]NSLog(@"Frequencies count: %lu", (unsigned long)[arrayofFrequencies count]);//the count here is correct, I have data in the array
要理解的是在viewDidLoad中调用tableView委托。那时数组计数为零。后来的数组中充满了对象。 reloadData
方法再次调用表的委托方法。
答案 1 :(得分:1)
您的Log Consol非常清楚地表明您的数据源方法是在数据加载之前调用的。
这是非常正常的,因为您在storyboard(或界面)或viewDidLoad中设置了数据源。
您必须在dataload
之后重新加载UITableView
试试这个:
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
arrayofFrequencies=[JSON valueForKeyPath:@"frequency"];
[tableView setDataSource:self];
[tableView reloadData];
} failure:nil];
您应该从界面构建器或故事板或viewDidLoad中删除数据源,以便UITableView不会自动重新加载两次。
答案 2 :(得分:0)
可能的猜测是,tableView委托更早被调用,但服务器的响应是在一段时间之后发生的,所以在得到响应之后尝试重新加载下面的tabview是代码。
-(void)GetFrequencies{
NSString *urla=@"http://xxxxxxxx";
NSString *uria = [urla stringByAppendingString:self.lien_satellite];
NSURL *urlFrequencies= [ NSURL URLWithString:uria];
NSLog(@"Frequencies URI: %@",uria); //correct URI
NSURLRequest *request = [NSURLRequest requestWithURL:urlFrequencies];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
arrayofFrequencies=[JSON valueForKeyPath:@"frequency"];
NSLog(@"Frequencies count: %lu", (unsigned long)[arrayofFrequencies count]);
// reload the table here
[tableView reloadData];
} failure:nil];
[operation start];
}
尝试这样做。