将JSON解析为表格视图错误索引(19)超出界限(19)

时间:2013-11-12 13:45:09

标签: ios json uitableview

我在我的iPhone应用程序中将JSON文件解析为表视图。 这是我的代码:

#import "DEMOSecondViewController.h"
#import "DEMONavigationController.h"
#import "PostsObject.h"
#import "RNBlurModalView.h"

#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
#define FONT_SIZE 14.0f

@interface DEMOSecondViewController ()
{
    NSInteger refreshIndex;
    NSArray *fbPost;
    NSArray *pic;
    NSArray *published;
}
@end

@implementation DEMOSecondViewController
@synthesize tweets;
@synthesize changeData;

- (void)refreshChannels:(id)sender {

    if (tweets.count == 0) return;

    // disable UI
    self.title = @"Updating...";
    self.navigationController.view.userInteractionEnabled = YES;
    refreshIndex = 0;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Posts";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Menu"
                                                                             style:UIBarButtonItemStylePlain
                                                                            target:(DEMONavigationController *)self.navigationController
                                                                            action:@selector(showMenu)];

    self.myTableView.separatorColor = [UIColor clearColor];

    changeData.selectedSegmentIndex = 0;

    [changeData addTarget:self action:@selector(segmentedControlSelectedIndexChanged:) forControlEvents:UIControlEventValueChanged];

    [self issueLoadRequest];
}

- (void)segmentedControlSelectedIndexChanged:(id)sender
{
    [self issueLoadRequest];
}

#pragma mark - Table view data source

- (void)issueLoadRequest
{
    if (changeData.selectedSegmentIndex == 0) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"website.php"]];
            [self performSelectorOnMainThread:@selector(receiveData:) withObject:data waitUntilDone:YES];
        });
    } else if (changeData.selectedSegmentIndex == 1){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"website.php"]];
            [self performSelectorOnMainThread:@selector(receiveData:) withObject:data waitUntilDone:YES];
        });
    } else if (changeData.selectedSegmentIndex == 2) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"website.php"]];
            [self performSelectorOnMainThread:@selector(receiveData:) withObject:data waitUntilDone:YES];
        });
    }
}

- (void)receiveData:(NSData *)data {
    if (changeData.selectedSegmentIndex == 0) {
        self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        [self.myTableView reloadData];
    } else if (changeData.selectedSegmentIndex == 1) {
        self.tweets1 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        [self.myTableView reloadData];
    } else if (changeData.selectedSegmentIndex == 2) {
        self.tweets2 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
        [self.myTableView reloadData];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (changeData.selectedSegmentIndex == 0) {
        return self.tweets.count;
    } else if (changeData.selectedSegmentIndex == 1) {
        return self.tweets1.count;
    } else {
        return self.tweets2.count;
    }
}

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


    // The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
    NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
    NSDictionary *tweet1 = [self.tweets1 objectAtIndex:indexPath.row];
    NSDictionary *tweet2 = [self.tweets2 objectAtIndex:indexPath.row];

    PostsObject *cell = (PostsObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"PostsObject" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    if (changeData.selectedSegmentIndex == 0) {
        cell.fbPost.text = [tweet objectForKey:@"message"];
        cell.published.text  = [tweet objectForKey:@"published"];
        cell.pic.image = [UIImage imageNamed:@"facebook_icon.png"];
    } else if (changeData.selectedSegmentIndex == 1) {
        cell.fbPost.text = [tweet1 objectForKey:@"tweet"];
        cell.published.text = [tweet1 objectForKey:@"posted"];
        cell.pic.image = [UIImage imageNamed:@"twitter_icon.png"];
    } else if (changeData.selectedSegmentIndex == 2) {
        cell.fbPost.text = [tweet2 objectForKey:@"message"];
        cell.published.text  = [tweet objectForKey:@"published"];
        cell.pic.image = [UIImage imageNamed:@"twitter_icon.png"];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 96;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (changeData.selectedSegmentIndex == 0) {
        //Öppna länken eller liknande
        int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
        NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:@"message"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];

        RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:@"Message" message:storyLink];
        [modal show];

        // Spit out some pretty JSON for the tweet that was tapped. Neato.
        NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
        NSLog(@"tweet:\n%@", formattedJSON);
    } else if (changeData.selectedSegmentIndex == 1) {
        //Öppna länken eller liknande
        int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
        NSString * tweetLink = [[tweets objectAtIndex: tweetLink] objectForKey:@"tweet"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:tweetLink]];

        RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:@"Message" message:tweetLink];
        [modal show];

        // Spit out some pretty JSON for the tweet that was tapped. Neato.
        NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
        NSLog(@"tweet:\n%@", formattedJSON);
    } else if (changeData.selectedSegmentIndex == 2) {
        //Öppna länken eller liknande
        int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
        NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:@"message"];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];

        RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:@"Message" message:storyLink];
        [modal show];

        // Spit out some pretty JSON for the tweet that was tapped. Neato.
        NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
        NSLog(@"tweet:\n%@", formattedJSON);
    }
}


@end

当我启动应用程序时,我发现它正确地将数据解析到表格视图中。但当我开始在列表中向下滚动时,应用程序崩溃并给我这个奇怪的错误:

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFArray objectAtIndex:]: index (19) beyond bounds (19)

有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

你不应该这样做:

// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
NSDictionary *tweet1 = [self.tweets1 objectAtIndex:indexPath.row];
NSDictionary *tweet2 = [self.tweets2 objectAtIndex:indexPath.row];

因为您无法保证所有数组中的所有数据都相同。在尝试仅访问相应的阵列之前,请检查配置属性(selectedSegmentIndex)。