2011-07-27 6 views
0

私はSBJSONフィードを使用してツイッターからSBJSONフレームワークの例を使ってデータをダウンロードしています。ダウンロードが完了すると、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は非同期です。ダウンロードが完了し、結果にtwitterArrayが設定されたら、[self.tableView reloadData]に電話する必要があります。これにより、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

' - (void)connectionDidFinishLoading:(NSURLConnection *)connection'メソッドの最後に' [self.tableView reloadData]; 'を追加しましたか?最初は0にする必要がありますが、ダウンロードと解析が完了すると実際のカウントが返されます。 –

+0

私の答えはPaul.sの具体的な説明で更新されました。彼が言ったように、このメソッドは最初は0行( 'nil'のように)をプリントアウトして返しますが、ダウンロードが終了すると再び呼び出されます。 –