-1

これは私のコードですViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UITableView *mainTableView;

    NSArray *news;
    NSMutableData *data;
}

@end

そして、ここにあるViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"News";

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURL *url = [NSURL URLWithString:@"http://google.com/external/search?query=hello"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[NSURLConnection alloc] initWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    [data appendData:theData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
    news = [responseDict objectAtIndex:0];
    [mainTableView reloadData];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

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

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [news count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];

    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
    }

    cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"];
    cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"title"];

    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

私が知る限り、JSON を辞書に入れるコードは間違っています。存在しないインデックスを見つけようとしているからです。代わりに JSON の配列を辞書に読み込むことができるように、このコードを変更する方法はありますか?

更新: .m ファイルの新しいコードは次のとおりです。

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"News";

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

    NSURL *url = [NSURL URLWithString:@"http://google.com/external/search?query=hello"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    data = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)theData
{
    [data appendData:theData];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
    //news = [responseDict objectAtIndex:0];
    // [mainTableView reloadData];
    if ([responseDict isKindOfClass:[NSArray class]]) {
        news = responseDict;
        [mainTableView reloadData];
    } else {
        NSLog(@"JSON Error.");
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    UIAlertView *errorView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"The download could not complete - please make sure you're connected to either 3G or Wi-Fi." delegate:nil cancelButtonTitle:@"Dismiss" otherButtonTitles:nil];
    [errorView show];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}

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

- (int)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [news count];
}

NSString *_getString(id obj)
{
    return [obj isKindOfClass:[NSString class]] ? obj : nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];

    if(cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MainCell"];
    }

    cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"]);
    cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"title"]);

    return cell;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
4

1 に答える 1

2

変化する

news = [responseDict objectAtIndex:0];

news = responseDict;

- (void)connectionDidFinishLoading:(NSURLConnection *)connectionメソッドで。

アップデート:

/* -viewDidLoad, just fix warning "unused var" */
// [[NSURLConnection alloc] initWithRequest:request delegate:self];
[NSURLConnection connectionWithRequest:request delegate:self];

-

/* connectionDidFinishLoading */
// NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
NSArray *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
//news = [responseDict objectAtIndex:0];
// [mainTableView reloadData];
if ([responseDict isKindOfClass:[NSArray class]]) {
        news = responseDict;
        [mainTableView reloadData];
} else {
        NSLog(@"JSON Error.");
}

-

NSString *_getString(id obj)
{
        return [obj isKindOfClass:[NSString class]] ? obj : nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
        // ...

       // cell.textLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"];
       // cell.detailTextLabel.text = [[news objectAtIndex:indexPath.row] objectForKey:@"title"];

        /** Your JSON value maybe NSNull */
        cell.textLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"metaScore"]);
        cell.detailTextLabel.text = _getString([[news objectAtIndex:indexPath.row] objectForKey:@"title"]);

        return cell;
}
于 2013-08-14T16:23:39.343 に答える