我喜欢在UITableView中显示时间轴,我正在使用此代码来获取推文:
- (void)viewDidLoad
{
[super viewDidLoad];
[self gettweets];
}
-(void)gettweets {
NSString *apiurl = [NSString stringWithFormat:@"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=idoodler"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:apiurl]];
NSError* error;
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *meta = [json valueForKeyPath:@"text"];
tweets = json;
NSLog(@"%@",meta);
}
我的日志显示了正确的推文。
然后我用它在UITableView中显示推文:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return 0;
return [tweets count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdenfifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdenfifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdenfifier];
}
cell.text = [tweets objectAtIndex:indexPath.row];
[tableView reloadData];
return cell;
}
我在.U文件中为UITableView创建了一个IBOutlet。我真的不知道我的错误是什么!
答案 0 :(得分:3)
最好做这样的事情:
NSString *apiurl = [NSString stringWithFormat:@"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=idoodler"];
NSError* error = nil;
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:apiurl] options: NSDataReadingUncached error:&error];
if (error)
{
// Something went wrong
}
else {
// Data fetched!
NSDictionary * json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
NSArray *meta = [json valueForKeyPath:@"text"];
// Setup your tweets array here!
[tableview reloadData];
}
同时删除[tableview reloadData];来自cellForRowAtIndexPath方法。
编辑: 另外,不要忘记将ViewController设置为接口构建器或viewDidLoad方法中的tableview的datatsource / delegate,如下所示:
[tableView setDelegate:self];
[tableView setDataSource:self];