UITableViewDelegate在单独的类中出错

时间:2014-05-07 14:31:04

标签: ios objective-c uitableview

我想在另一个类中分隔UITableViewDataSourceUITableViewDelegate,以便在UITableView

中减少和更改委托

这是我的代码 的 GroupTableController.h

@interface GroupTableController : NSObject <UITableViewDataSource, UITableViewDelegate>

  {
     OutlayGroupsCollection *outlayGroupsCollection;
     Car *currentCar;
     Period *currentPeriod;
  }

-(void) setCar:(Car*) currentCar andPeriod:(Period*) currentPeriod;
-(int) total;
@end

GroupTableController.m

@implementation GroupTableController

-(void) setCar:(Car*) car andPeriod:(Period*) period
{
  currentCar = car;
  currentPeriod = period;
}

-(int) total
{
  if(outlayGroupsCollection == nil){
            outlayGroupsCollection = [OutlayGroupsCollection new];
        }

    NSMutableArray *list = [outlayGroupsCollection list:currentCar     forPeriod:currentPeriod];
    int result = 0;
    for (OutlayGroup *group in list) {
        result=result+group.sum;
    }
return result;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    OutlayGroupCell *cell = (OutlayGroupCell*)[tableView dequeueReusableCellWithIdentifier:@"OutlayGroupCell"];

    if (cell==nil) {
        cell = [[OutlayGroupCell alloc] init];
    }

    OutlayGroup *group = [[outlayGroupsCollection list:currentCar forPeriod:currentPeriod ] objectAtIndex:indexPath.section];
    cell.typeView.text = [OutlayType getName:[group type]];
    cell.sumView.text = [NSString stringWithFormat:@"%d", [group sum]];

    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section     {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if(outlayGroupsCollection==nil){
        outlayGroupsCollection = [OutlayGroupsCollection new];
    }
    return [[outlayGroupsCollection list:currentCar forPeriod:currentPeriod ] count];
}


@end

我接下来要绑定它:

GroupTableController *gtd = [[GroupTableController alloc] init];

mainTableView.delegate = gtd;
mainTableView.dataSource = gtd;
[(GroupTableController*)mainTableView.delegate setCar: currentCar andPeriod: currentPeriod];

但是,我收到了错误

[GroupTableController numberOfSectionsInTableView:]: message sent to deallocated instance 0x9e4d640

我做错了什么!? (我是Objective C的新人!)

1 个答案:

答案 0 :(得分:1)

问题在于delegate的{​​{1}}和dataSource属性类型为UITableView,这意味着它们不会为您保留assign

您需要确保在创建控制器(gtd)后,将其保留为属性。