我从多次呈现给我的UITableView的服务返回数据。我移动了在connectionDidFinishLoading委托中填充我的表的代码。这是该代码的正确位置吗?
我有一个NSMutableData * receivedData;在我的.m文件的顶部,我已经实现了正确的委托并覆盖了正确的方法。
我只是想知道我在这里缺少什么,或者我只能在表格视图中查看我的JSON数据。
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[receivedData setLength:0];
NSLog(@"%@",response);}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"Succeeded! Received %d bytes of data",[data length]);
receivedData = [[NSMutableData alloc] init];
[receivedData appendData:data];}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *error = nil;
// Get the JSON data from the website
id result = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&error];
if ([result isKindOfClass:[NSArray class]]) {
for (NSArray *item in result) {
NSArray *category = [item valueForKey:@"CategoryName"];
[dataArray addObject:category];
}
}
else {
NSDictionary *jsonDictionary = (NSDictionary *)result;
for(NSDictionary *item in jsonDictionary)
NSLog(@"Item: %@", item);
}
[self.tableView reloadData];
NSLog(@"Finished");}
答案 0 :(得分:1)
我相信你有一行错误
receivedData = [[NSMutableData alloc] init];
每次收到数据时,您都会再次初始化对象。
我建议您将这个页面http://nsscreencast.com/episodes/6-afnetworking用于您的JSON部分。