UITableview会自动在UITabbarcontroller中重新加载

时间:2015-01-26 10:43:57

标签: ios objective-c uitableview uitabbarcontroller realm

我有一个uitabbarcontroller,在标签页中,我有UIViewcontrolleruitableview。问题是,当我切换到另一个选项卡,然后再次切换到选项卡时,uitableview会自动重新加载。

以下是我的代码,我在fetchAppointments

中致电viewWillappear
-(void)fetchAppointments:(NSDate *)startDate andEndDate:(NSDate *)endDate{
    Webservice_2 *web = [[Webservice_2 alloc]init];
    [web fetchAppointmentsWithStart:startDate andEndDate:endDate onCompletion:^(BOOL finished) {
        if(finished){
            [self loadData:_strDate];
            [HUD hide:YES];
        }
    }];

}
-(void)loadData:(NSString *)today{
    NSDate *start = [NSDate dateWithTimeIntervalSince1970:[today floatValue]];

    NSCalendar *calender = [NSCalendar currentCalendar];
    NSCalendarUnit units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *components = [calender components:units fromDate:start];
    components.timeZone = [NSTimeZone localTimeZone];


    NSDateComponents *dateComps = [[NSDateComponents alloc]init];
    [dateComps setDay:[components day]];
    [dateComps setMonth:[components month]];
    [dateComps setYear:[components year]];
    [dateComps setHour:0];
    [dateComps setMinute:0];
    [dateComps setSecond:0];
    NSDate *startDate = [calender dateFromComponents:dateComps];


    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *offset = [[NSDateComponents alloc] init];
    [offset setDay:1];
    NSDate *endDate =  [calendar dateByAddingComponents:offset toDate:startDate options:0];


    NSPredicate *predicate = [NSPredicate predicateWithFormat:
                              @"app_start >= %@ AND app_end <= %@",startDate,endDate];

    appointments = [[Appointment_2 objectsWithPredicate:predicate]sortedResultsUsingProperty:@"app_start" ascending:YES];    NSLog(@"appointments is %@",appointments);

    [tableAppointments reloadData];
}

这是我得到的错误:

*** Terminating app due to uncaught exception 'RLMException', reason: 'Index is out of bounds.'

这是因为在我的CellForRowAtIndexPath我这样做:

 Appointment_2 *appointment = [appointments objectAtIndex:indexPath.row];

额外信息

  • 我使用Realm存储我的数据。和约会_2是RLMObject
  • 同样在fetchAppointmentsWithStart我删除了所有对象,然后再次添加它们。

我的问题是为什么我的tableview会自动重新加载?

提前致谢!!

1 个答案:

答案 0 :(得分:0)

您自己回答了这个问题:您的UITableView会自动重新加载,因为您在fetchAppointments中致电viewWillAppear,这会导致重新加载数据(通过调用loadData: )以及随后的UITableView重新加载。

每次在标签栏中点击某个项目时,都会调用相应的视图控制器的viewWillAppear方法。

希望我的回答很清楚,如果您有其他问题,请告诉我们!

<强>更新 顺便说一句,快速解决崩溃问题可能是检查appointments数组实际上是否包含了您尝试从中获取的元素:

Appointment_2 *appointment = nil;
if([appointments count] <= indexPath.row){
  appointment = [appointments objectAtIndex:indexPath.row];
}