2011-07-27 25 views
0

我使用SBJSON框架示例使用JSON訂閱源從Twitter下載數據。一旦下載完成,我得到numberofrows爲0.我必須等待數據下載之前,或者我錯過了我的代碼中的任何數組的初始化?在numberofrowsinsection中計數0

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

回答

4

除非您使用+sendSynchronousRequest:returningResponse:error:,否則NSURLConnection是異步的。您需要在下載完成後致電[self.tableView reloadData],並且您已將twitterArray設置爲您的結果。這將強制tableView重新讀取其所有數據源/委託方法。

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

我已經更新了我的代碼,如上所示。但仍然給我計數0. – lifemoveson

+2

您是否已將'[self.tableView reloadData];'添加到' - (void)connectionDidFinishLoading:(NSURLConnection *)連接方法的末尾?它應該最初給0,但一旦下載和解析完成應該返回實際的計數。 –

+0

與Paul.s的具體澄清更新了我的答案。就像他說的那樣,該方法最初會打印出(並返回)0行(因爲它是'nil'),但是在完成下載後,它將再次被調用。 –