簡體   English   中英

將json數據添加到UITableView中

[英]Adding json data into UITableView

這是我的viewController.m文件中的示例getData方法

-(void) getData {
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://twitter.com/statuses/public_timeline.json"]];

// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];

// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
    NSString *text = [status objectForKey:@"text"];
    // You can retrieve individual values using objectForKey on the status NSDictionary
    // This will print the tweet and username to the console
    NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]);

}
}

我想要做的是取[[status objectForKey:@"user"]並使其成為表視圖中單元格的名稱,我將如何進行此操作?

編輯:好的,所以我把它變成了一個字符串,但現在我嘗試加載它崩潰說[__NSCFDictionary isEqualToString:]: unrecognized selector sent to instance 0x6892b60'

它顯示了緊靠cell.textLabel.text = [[statusArray objectAtIndex:indexPath.row] objectForKey:@"user"];旁邊的線程cell.textLabel.text = [[statusArray objectAtIndex:indexPath.row] objectForKey:@"user"]; Thread 1 SIGABRT

在getData函數中收集數組中的所有數據。 說它是statusArray。 現在,從UItableViewController派生出一個viewcontroller。 在此類NSArray類型中創建一個成員,並為其分配上面的數組。 將以下函數寫入控制器類。

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

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

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

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    cell.textLabel.text = [statusArray objectAtIndex:indexPath.row] objectForKey:@"user"];
    return cell;
}

實現UITableViewDataSource協議:

  • tableView:numberOfRowsInSection: - 返回“狀態”的數量
  • tableView:cellForRowAtIndexPath: - 返回一個UITableViewCell,其textLabel.text設置為您的文本。

Apple的文檔中有很多示例,包括使用Xcode的“Master-Detail App”模板創建新應用程序時獲得的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM