我使用SBJSON Framework示例使用JSON feed从twitter下载数据。下载完成后,我将numberofrows改为0.我是否必须在下载数据之前等待,或者我在代码中缺少任何数组的启动?
- (void)viewDidLoad {
[super viewDidLoad];
// Add the view controller's view to the window and display.
responseData = [[NSMutableData data] retain];
self.twitterArray = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:@"http://search.twitter.com/search.json?q=mobtuts&rpp=5"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[super viewWillAppear:animated];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *results = [responseString JSONValue];
self.twitterArray = [results objectForKey:@"results"];
[self.tableView reloadData]; // Correct way
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
NSLog(@"count : %d", [self.twitterArray count]); // Gets the count 0 here.
return [self.twitterArray count];
}
答案 0 :(得分:4)
除非您使用+sendSynchronousRequest:returningResponse:error:
,否则NSURLConnection是异步的。下载完成后,您需要致电[self.tableView reloadData]
,并且twitterArray
设置为您的结果。这将强制tableView重新读取其所有数据源/委托方法。
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *results = [responseString JSONValue];
self.twitterArray = [results objectForKey:@"results"];
[self.tableView reloadData]; // <-- add this here
}