我有一个应用程序,它从 3 个共享的 Google 日历中获取事件并将其显示在表格视图中。
我想实现拉刷新,但是如果我在加载数据之前放开拉,应用程序会一直崩溃。(如果我保持拉动几秒钟一切都很好 - 如果我立即松开它会崩溃。
代码:
-(void)viewDidLoad
{
[super viewDidLoad];
UIRefreshControl *refresh = [[UIRefreshControl alloc] init];
refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"Pull to Refresh"];
[refresh addTarget:self action:@selector(getEvents) forControlEvents:UIControlEventValueChanged];
self.refreshControl = refresh;
startDates = [[NSMutableArray alloc] init];
[self getEvents];
}
- (void)stopRefresh
{
[self.refreshControl endRefreshing];
}
-(void)getEvents
{
[startDates removeAllObjects];
startDates = [NSMutableArray array];
sectionEntries = [NSMutableArray array];
entries = [NSMutableArray array];
sortedStartDates = [[NSArray alloc]init];
_imageForCalendarType = [[NSDictionary alloc]init];
_imageForCalendarType = @{
@"The Irish House Music Calendar" : [UIImage imageNamed:@"music.png"]
, @"FixedEvents-Student Night" : [UIImage imageNamed:@"student.png"]
, @"FixedEvents-Ladies Night" : [UIImage imageNamed:@"cocktail.png"]
, @"AppTest" : [UIImage imageNamed:@"football.png"]
};
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:sportsCalendarURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
NSData* data2 = [NSData dataWithContentsOfURL:musicCalendarURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data2 waitUntilDone:YES];
NSData* data3 = [NSData dataWithContentsOfURL:fixedCalendarURL];
[self performSelectorOnMainThread:@selector(fetchedData:) withObject:data3 waitUntilDone:YES];
// Reload table view - UI operation, so must be run on main thread
dispatch_async(dispatch_get_main_queue(), ^{
sortedStartDates = [startDates sortedArrayUsingSelector:@selector(compare:)];
[self.tableView reloadData];
[self performSelector:@selector(stopRefresh) withObject:nil afterDelay:2.5];
});
});
}
它在 cellForRowAtIndexPath 方法的这一行中给了我一个 SIGABRT 错误:
NSInteger index = [self getRow:sortedStartDates[indexPath.section]]; // get correct index for sectionEntries
错误: * 由于未捕获的异常“NSRangeException”而终止应用程序,原因:“* -[__NSArrayI objectAtIndex:]: index 4 beyond bounds for empty array”
似乎错误是因为我的 startDates NSMutableArray 中没有数据,但如果我评论 [startDates removeAllObjects] 行,我会得到多余的单元格。