0

我正在使用本教程来练习创建一个非常基本的 Twitter 应用程序:http: //www.codeproject.com/Articles/312325/Making-a-simple-Twitter-app-using-iOS-5-Xcode-4-2 #setting-up-the-table-view

我的应用程序的唯一区别是我只使用 tableView ViewController。我似乎无法让它工作。

视图控制器.h

@interface ViewController : UIViewController {


NSArray *tweets;
}
-(void)fetchTweets;

@property (retain, nonatomic) IBOutlet UITableView *tableView;

@end

视图控制器.m

#import "ViewController.h"
#import "Twitter/Twitter.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize tableView = _tableView;

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self fetchTweets];
}

- (void)fetchTweets
{
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData* data = [NSData dataWithContentsOfURL:
                    [NSURL URLWithString: @"https://api.twitter.com/1/statuses/public_timeline.json"]];

    NSError* error;

    tweets = [NSJSONSerialization JSONObjectWithData:data
                                             options:kNilOptions
                                               error:&error];

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
});
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return tweets.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"TweetCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

NSDictionary *tweet = [tweets objectAtIndex:indexPath.row];
NSString *text = [tweet objectForKey:@"text"];
NSString *name = [[tweet objectForKey:@"user"] objectForKey:@"name"];

cell.textLabel.text = text;
cell.detailTextLabel.text = [NSString stringWithFormat:@"by %@", name];

return cell;
}

- (void)viewDidUnload
{
_tableView = nil;
[self setTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
    return YES;
}
}

@end
4

1 回答 1

1

您忘记为您的表定义委托和数据源,并且没有按照我在您的代码中看到的正确实施协议,

试试你的 .h 文件:

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    // your implementation...
}

并在您的 .m 文件中viewDidLoad

self.tableView.dataSource = self;
self.tableView.delegate = self;

在您为此表定义委托和数据源之前,该numberOfRows, cellForRow, 等... 方法将不起作用:)

于 2012-04-16T20:53:56.737 回答