Skip to content

Instantly share code, notes, and snippets.

@inonb
Created July 22, 2012 02:31
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save inonb/3157988 to your computer and use it in GitHub Desktop.
Save inonb/3157988 to your computer and use it in GitHub Desktop.
[iOS] JSONをパースして配列を取得・テーブルビューに表示
- (void)viewDidLoad
{
[super viewDidLoad];
// 空の配列を用意
self.items = [NSArray array];
[self getJSON];
}
- (void)getJSON
{
NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/jp/rss/topfreeapplications/limit=10/json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
// アプリデータの配列をプロパティに保持
self.items = [[jsonDictionary objectForKey:@"feed"] objectForKey:@"entry"];
// TableView をリロード
[self.tableView reloadData];
}];
}
// セルの数を設定
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [items 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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDictionary *item = [items objectAtIndex:indexPath.row];
// アプリ名を設定
cell.textLabel.text = [[item objectForKey:@"im:name"] objectForKey:@"label"];
return cell;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment