使用JSON数据滚动问题表视图

时间:2014-01-04 22:53:03

标签: ios json parsing uitableview

我正在将位于我服务器上的JSON文件中的一些数据解析为我的表视图。 当我启动应用程序时,应用程序成功将数据下载到我的表视图,但当我开始滚动时,应用程序崩溃。

这是我的代码:

#import "FirstViewController.h"
#import "YoutubePost.h"
#import "AFNetworking.h"

@interface FirstViewController ()

@end

@implementation FirstViewController
@synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView, movies = _movies;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Videos", @"Videos");
        self.tabBarItem.image = [UIImage imageNamed:@"newtab1"];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self.navigationController setNavigationBarHidden:YES];

    self.tableView.separatorColor = [UIColor clearColor];

    // Setting Up Activity Indicator View
    self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.activityIndicatorView.hidesWhenStopped = YES;
    self.activityIndicatorView.center = self.view.center;
    [self.view addSubview:self.activityIndicatorView];
    [self.activityIndicatorView startAnimating];
    self.tableView.separatorColor = [UIColor clearColor];

    // Initializing Data Source
    self.movies = [[NSArray alloc] init];

    NSURL *url = [[NSURL alloc] initWithString:@"http://my-website.com/link-to-json.php?name=Name&orderby=published"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        self.movies = JSON;
        [self.activityIndicatorView stopAnimating];
        [self.tableView reloadData];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation start];
}

// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.movies && self.movies.count) {
        return self.movies.count;
    } else {
        return 0;
    }
}

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

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

    YoutubePost *cell = (YoutubePost *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    if (cell == nil)
    {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YoutubePost" owner:self options:nil];
        cell = [nib objectAtIndex:0];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

    }

    NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
    cell.title.text = [movie objectForKey:@"title"];

    NSURL *url = [[NSURL alloc] initWithString:[movie objectForKey:@"link"]];

    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];    
    NSString * storyLink = [[_movies objectAtIndex: storyIndex] objectForKey:@"link"];

    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
    NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
    NSLog(@"tweet:\n%@", formattedJSON);
}

@end

有什么问题?我看到数据成功下载到我的自定义表视图单元格,但每次我尝试向下滚动应用程序崩溃。请帮我解决这个问题。

感谢。

3 个答案:

答案 0 :(得分:2)

纠正这个:

    // Initializing Data Source
    //self.movies = [[NSArray alloc] init];

    NSURL *url = [[NSURL alloc] initWithString:@"http://my-website.com/link-to-json.php?name=Name&orderby=published"];
    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        self.movies = [[NSArray alloc] initWithArray:JSON];
        [self.activityIndicatorView stopAnimating];
        [self.tableView reloadData];

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
    }];

    [operation start];

在您的YouTubePost Nib中添加标识符“YouTubePost”:

enter image description here

并且在您的YouTubePost笔尖中选择您的标题UILabel并在检查员中更改: Line Breaks

要:

Line Breaks

或更改:

Lines 2

要:

Lines 1

这将完成这项工作。

答案 1 :(得分:0)

更改以下行:

if (cell == nil)
{
    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"YoutubePost" owner:self options:nil];
    cell = [nib objectAtIndex:0];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

}

像这样:

if (cell == nil)
{
     UINib *nib = [UINib nibWithNibName:@"YoutubePost" bundle:nil];

    [tableView registerNib:nib forCellReuseIdentifier:@"YoutubePost"];

    tableViewCell = [tableView dequeueReusableCellWithIdentifier:@"YoutubePost"];
}

答案 2 :(得分:0)

您似乎没有在JSON中检查[NSNull null]。以下代码可能会为您[NSNull null]而不是NSDictionary

NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];

您应该在调用reloadData

之前对其进行过滤 同样,此行也可能返回[NSNull null]

cell.title.text = [movie objectForKey:@"title"];

你需要准备好处理这种情况。这可能会对您有所帮助:
Replace all NSNull objects in an NSDictionary