滚动浏览表视图'NSRangeException'时关闭应用程序

时间:2013-03-03 20:39:37

标签: ios xcode arrays uitableview terminate

我的应用程序中的Twitter提要功能已经完美无缺,但我今天再次测试它,但每当我滚动到第4条推文时,应用程序就会失效。我得到的错误是:

  

由于未捕获的异常'NSRangeException'而终止应用程序,原因:' - [__ NSCFArray objectAtIndex:]:index(3)超出bounds(3)'

这是我的代码

#import "ThirdViewController.h"
#import "ODRefreshControl.h"


@interface ThirdViewController ()

@end

@implementation ThirdViewController

-(void)bannerViewDidLoadAd:(ADBannerView *)banner {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:1];
[UIView commitAnimations];
}

- (void)bannerView:(ADBannerView *)
banner didFailToReceiveAdWithError:(NSError *)error
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1];
[banner setAlpha:0];
[UIView commitAnimations];
}


@synthesize tableView = _tableView;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
 return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (BOOL)shouldAutorotate
{
return NO;
}

- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskPortrait;
}

-(void)TableView:(UITableView *)TableView didFailLoadWithError:(NSError *)error {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Can't connect. Please check your internet Connection" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];

}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
ODRefreshControl *refreshControl = [[ODRefreshControl alloc] initInScrollView:self.tableView];
[refreshControl addTarget:self action:@selector(dropViewDidBeginRefreshing:) forControlEvents:UIControlEventValueChanged];
// Do any additional setup after loading the view.
[self fetchTweets];
self.tableView.dataSource = self;
self.tableView.delegate = self;
UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background.png"]];
[tempImageView setFrame:self.tableView.frame];

self.tableView.backgroundView = tempImageView;



}


- (void)fetchTweets
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData* data = [NSData dataWithContentsOfURL:
                    [NSURL URLWithString: @"http://search.twitter.com/search.json?q=from:bikechannel"]];

    NSError* error;

    tweets = [NSJSONSerialization JSONObjectWithData:data
                                             options:kNilOptions
                                               error:&error];

    NSLog(@"Tweets %@", tweets);

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
});
}

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

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

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}

NSArray *tweetsArray = [tweets valueForKey:@"results"];
NSDictionary *tweet = [tweetsArray objectAtIndex:indexPath.row];


NSString *text = [tweet objectForKey:@"text"];
//NSString *name = [[tweet objectForKey:@"user"] objectForKey:@"name"];

cell.textLabel.text = text;
//cell.detailTextLabel.text = [NSString stringWithFormat:@"by %@", name];

return cell;
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath {

NSLog(@"Row %d selected", indexPath.row);
}


- (void)dropViewDidBeginRefreshing:(ODRefreshControl *)refreshControl
{
double delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    [self fetchTweets];
    [refreshControl endRefreshing];
});
}

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


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

@end

我知道如何解决这个问题吗?

2 个答案:

答案 0 :(得分:2)

您将以numberOfRows的形式返回UITableView:tweets count 但是,在cellForRowAtIndexPath上,您将使用数组:

NSArray *tweetsArray = [tweets valueForKey:@"results"];

所以要么你需要设置tweetsArray大小的行数,要么使用CellForRowAtIndexPath中的tweets数组

答案 1 :(得分:1)

你的问题是你使用推文作为计数,

您的tweets大小为3但tweetsArray大小为4的情况,因此您的数组超出范围,

使用tweetsArray填充tableview的行,因此您应该返回tweetsArray而不是tweets

的计数

.h

@property (strong,nonatomic)NSArray *tweetsArray;

.m

     - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [tweetArray count]; // this should be number of rows you have data in the array
    }

在解析推文中的json数据之后,再将这行代码放在fetchtweets方法中

NSArray *tweetsArray = [tweets valueForKey:@"results"];
相关问题