2014-05-07 58 views
0

我想在其他類UITableView錯誤的UITableViewDelegate在單獨的類

這是我的代碼 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分開UITableViewDataSourceUITableViewDelegate減少和改變委託

@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 

我做什麼錯!? (我的目標C新!)

+2

你可以顯示整個方法是你初始化'gtd'。您需要在某處保留對'gtd'的強引用,因爲您使用的ARC和'tableView'的'delegate'和'dataSource'都是弱引用,它會在方法結尾處釋放'gtd'。 –

+0

是的!你是對的!強烈的參考解決了我的問題!謝謝! –

回答

1

的問題是delegatedataSource物業類型UITableViewassign,這意味着他們將不會保留gtd你。

您需要確保在創建控制器(gtd)後,您將其保留爲屬性。

+0

是的,我把「gtd」設置爲「@property(strong,nonatomic)GroupTableController * groupTableController;」這解決了我的問題。 –