AppDelegate中的NSURLConnection和SBJSon

时间:2012-01-27 13:50:50

标签: ios5 xcode4.2 sbjson

我在使用ARC和Storyboard(iOS 5)的xCode 4.2中。我想将推文放到我的TableViewController中。当我放置我的NSURLConnection时,一切都很顺利,我已经在委托中的推文(NSArray)中得到了响应。问题是它没有填充表视图。我正在使用SBJson接收数据。我错过了什么吗?

AppDelegate.m

#import "AppDelegate.h"
#import "TwitterViewController.h"
#import "SBJson.h"


@implementation AppDelegate

@synthesize window = _window;

@synthesize receivedData;
@synthesize tableViewController;
@synthesize tweets;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    tweets = [NSMutableArray array];
    NSURLRequest *request = [NSURLRequest requestWithURL:
                             [NSURL URLWithString:@"http://search.twitter.com/search.json?q={username}&rpp=5"]];
    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

    if (theConnection) {
        receivedData = [NSMutableData data];
    }
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{

    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);


    NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];

    NSDictionary *results = [responseString JSONValue];

    NSArray *allTweets = [results objectForKey:@"results"];

    [tableViewController setTweets:allTweets];
}
@end

这是我的表视图控制器中的委托方法。

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

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

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

    NSDictionary *aTweet = [tweets objectAtIndex:[indexPath row]];



    NSString *textFrom = [aTweet objectForKey:@"text"];
    cell.textLabel.text = textFrom;


    return cell;
}

我真的需要一些建议。

1 个答案:

答案 0 :(得分:0)

表重新加载。天哪!我学会了!