简体   繁体   中英

Count 0 in numberofrowsinsection

I am downloading data from twitter using JSON feed by using SBJSON Framework example. Once the downloading is done I get numberofrows to 0. Do I have to wait before the data is downloaded or am I missing any initilization of array in my code ?

- (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];
 }

NSURLConnection is asynchronous unless you use +sendSynchronousRequest:returningResponse:error: . You need to call [self.tableView reloadData] once your download completes and you have twitterArray set to your results. This will force the tableView to re-read all its datasource/delegate methods.

- (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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM