滚动表视图“NSRangeException”时应用程序关闭

Posted

技术标签:

【中文标题】滚动表视图“NSRangeException”时应用程序关闭【英文标题】:App shutting down when scrolling through table view 'NSRangeException' 【发布时间】:2013-03-03 20:39:37 【问题描述】:

我的应用程序中的 twitter 提要功能运行良好,但我今天再次对其进行了测试,但每当我滚动到第 4 条推文时,应用程序应该会关闭。我得到的错误是:

由于未捕获的异常“NSRangeException”而终止应用程序,原因:“-[__NSCFArray objectAtIndex:]: index (3) beyond 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

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

【问题讨论】:

【参考方案1】:

您将作为 numberOfRows 返回 UITableView:tweets count 然而,在 cellForRowAtIndexPath 上,您将其用作数组:

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

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

【讨论】:

我的 tweetsArray 大小是多少? 我建议你阅读一些关于在 Xcode 中调试的内容。对你有很大帮助。 好的,我会的,但是我怎么会发现这个问题,因为我需要尽快解决这个问题【参考方案2】:

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

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

正如使用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"];

【讨论】:

当您执行此日志语句NSLog(@"Tweets %@", tweets); 并且 tweets 是可变数组或字典时,您在控制台上得到什么? 当你返回推文计数时,不要尝试使用.将其作为属性访问,尝试像这样访问它return [tweets count]; 我从来没有真正使用过 nslog 或断点,我在整个编码方面不是很先进。我看了一个关于它的教程,但我仍然无法做到或真正理解你所说的。推文是我认为的字典。 好吧,我建议你学习解析以及如何在 ios 中使用 TableViews,那里有很多教程,除非你知道如何做基本的,否则尝试解决问题是没有用的东西,至少你可以阅读你自己的代码。 我知道如何解析,这个代码在我运行它时有效,并且推文确实显示只是突然之间,当我向下滚动时它停止工作,如果我使用不同的用户喂它工作正常。

以上是关于滚动表视图“NSRangeException”时应用程序关闭的主要内容,如果未能解决你的问题,请参考以下文章

xcode ios NSRangeException 创建子视图

当视图模型@Published 更改时,SwiftUI 列表因“NSRangeException”而崩溃

iphone dev - 如何捕获异常'NSRangeException'

自动展开 UITableView - NSRangeException

获取异常'NSRangeException'

NSRangeException - 无法移除观察者