2012-07-27 4 views
4

주어진 섹션에 모든 금액 라벨을 추가하고 섹션 헤더에 합계를 표시하고 싶습니다. 내 테이블보기가 이렇게 보입니다.coreData에서 검색된 값과 표시 섹션의 합계

섹션 헤더 - 2012년 12월 7일

categoryName Amount 
Groceries  100 
    Social  100 

섹션 헤더 - 2012년 10월 4일

categoryName Amount 
    Gas   500 
    Social  600 

가 지금은 1 섹션 header.and 1100 총 (200)를 표시 할
: 다음 헤더에

-(IBAction)bydate:(id)sender 
{ 
[self.expenseArray removeAllObjects]; 
[self.expenseArrayCount removeAllObjects]; 

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 

for(NSManagedObject *records in self.listOfExpenses){ 
    NSString *compareDates = [dateFormatter stringFromDate:[records valueForKey:@"date"]]; 
    BOOL isAvail = NO; 
    for (int i = 0; i<[self.expenseArray count]; i++){ 
     if([compareDates isEqualToString:[self.expenseArray objectAtIndex:i]]) 
      isAvail = YES; 
    } 
    if(!isAvail) 
     [self.expenseArray addObject:compareDates]; 
} 
int count = 0; 
for (int i = 0 ; i < [self.expenseArray count] ; i ++){ 
    NSString *compareDates = [self.expenseArray objectAtIndex:i]; 
    for(NSManagedObject *info in self.listOfExpenses){ 
     if([compareDates isEqualToString:[dateFormatter stringFromDate:[info valueForKey:@"date"]]]) 
      count++; 
    } 
    [self.expenseArrayCount addObject:[NSNumber numberWithInt:count]]; 
    count = 0; 
} 
[self.byDateTab reloadData]; 
[dateFormatter release]; 
} 

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //not posting un necessary code. 

    else if (tableView == self.byDateTab) 
{ 
    for(int i = 0; i < [self.expenseArrayCount count];i++) 
    { 
     if(indexPath.section == 0) 
     { 
      NSManagedObject *records = nil; 
      records = [self.listOfExpenses objectAtIndex:indexPath.row]; 
      self.firstLabel.text = [records valueForKey:@"category"]; 
      self.secondLabel.text = [records valueForKey:@"details"]; 
      NSString *amountString = [NSString stringWithFormat:@"%@",[records valueForKey:@"amount"]]; 
      self.thirdLabel.text = amountString; 
     } 
     else if (indexPath.section == i) 
     { 
      int rowCount = 0; 
      for(int j=0; j<indexPath.section; j++) 
      { 
       rowCount = rowCount + [[self.expenseArrayCount objectAtIndex:j]intValue]; 
      } 
      NSManagedObject *records = nil; 
      records = [self.listOfExpenses objectAtIndex:(indexPath.row + rowCount) ]; 
      self.firstLabel.text = [records valueForKey:@"category"]; 
      self.secondLabel.text = [records valueForKey:@"details"]; 
      NSString *amountString = [NSString stringWithFormat:@"%@",[records valueForKey:@"amount"]]; 
      self.thirdLabel.text = amountString; 

     } 
    } 
} 


-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
NSString *title = [[[NSString alloc]init]autorelease]; 
if(tableView == self.byDateTab) 
    title = [self.expenseArray objectAtIndex:section]; 
return title; 
} 

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section 
{ 
UIView *headerView = [[[UIView alloc]init] autorelease]; 
if(tableView == self.byDateTab){ 
    headerView.frame = CGRectMake(310, 0, tableView.bounds.size.width, 30); 
    [headerView setBackgroundColor:[UIColor colorWithRed:149.0/255 green:163.0/255 blue:173.0/255 alpha:1]]; 
    UILabel *leftLabel = [[[UILabel alloc]initWithFrame:CGRectMake(10, 3, tableView.bounds.size.width-10, 18)]autorelease]; 
    leftLabel.text = [self tableView:tableView titleForHeaderInSection:section]; 
    leftLabel.textColor = [UIColor whiteColor]; 
    leftLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:17.0]; 
    leftLabel.backgroundColor = [UIColor clearColor]; 
    [headerView addSubview:leftLabel]; 

    NSNumberFormatter *formatter = [[NSNumberFormatter alloc]init]; 
    NSString *a = [formatter currencySymbol]; 

    UILabel *rightLabel = [[[UILabel alloc]initWithFrame:CGRectMake(250, 3, tableView.bounds.size.width-10, 18)]autorelease]; 
    rightLabel.text = [NSString stringWithFormat:@"(%@)",a]; 
    rightLabel.textColor = [UIColor whiteColor]; 
    rightLabel.font = [UIFont fontWithName:@"AmericanTypewriter" size:17.0]; 
    rightLabel.backgroundColor = [UIColor clearColor]; 
    [headerView addSubview:rightLabel]; 



} 
+0

섹션의 레코드를 반복하고 총 금액을 반환하는 메서드를 작성해야합니다. 귀하의 코드는 이해하기 쉽지 않습니다. 나는'tableView : cellForRowAtIndexPath :'내부의 루프 목적을 이해하지 못한다. – florian

답변

0

당신은이 방법을 구현해야
주어진 섹션의 제목을 반환합니다. 그래서 어떤 레코드가 섹션 번호와 일치하는지 알아야하고 총량을 계산하기 위해 레코드를 반복해야합니다.
이 메서드를 호출 할 때마다 각 섹션의 총 용량을 계산하지 않으려면 위의 메서드를 사용하여이 작업을 수행하는 것이 좋습니다. 당신이 당신의 데이터를로드 만이 작업을 수행으로
당신은 곧 "미리 계산"제목의 배열을 만들 수 있습니다

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
    return [titles objectAtIndex:section]; 
} 
+0

질문을 편집하고이 방법의 코드를 제공 할 수 있습니까? – florian

+0

코드가 업데이트되었습니다 ..! –

0

논리는 매우 간단합니다. 난 정말 코드에 깊은 가고 싶어하지 않기 때문에이 덩어리는 여러분에게 필요한 설명을 줄 것이다

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    NSArray *sectionArray = [mySectionsDictionary objectForKey:[NSString stringWithFormat:@"%d", section]]; 
    int total = 0; 
    for (MyCustomCoreDataObject *object in sectionArray) { 
    total += object.amount.intValue; 
    } 
    return [NSString stringWithFormat:@"%d", total]; 
} 
+0

나는 사전을 사용하지 않았다. 나는 나의 코드를 업데이트했다. –

0

참고 (난 당신이 fetchResultController를 사용하지 않는 내가로 사용하는 않는 것을 볼 수 이 작업과 핵심 데이터 엔티티를 표시하는 테이블보기가있는 다른 작업에 도움이 될 것입니다. fetchResultController와

는 :

당신은 가져온 엔티티 클래스 (당신이 fetchResultController에 가져 엔티티)에 totalAmount있는 NSString을 추가해야합니다.

그런 다음 클래스에 추가 작업을 추가하십시오. inside는 계산을 작성하여 총 금액을 문자열로 얻습니다.

-(NSString*)totalAmount{ 
    NSInteger amount = 0; 
    //do your calculation here 
    return [NSString stringWithFormat:@"amount = %i",amount]; 
} 

후 결과를 가져 컨트롤러에서이 각 섹션에 대한 totalAmount 문자열을 반환됩니다 섹션 이름 키 경로로 totalAmount을 통과

:

NSFetchedResultsController *fetchedResultsController = 
[[NSFetchedResultsController alloc] initWithFetchRequest:request 
            managedObjectContext:managedObjectContext 
             sectionNameKeyPath:@"totalAmount" cacheName:nil]; 

는 그런 다음 섹션 헤더 방법을 편집 테이블보기 때문에

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    // Return the number of sections. 
    return ([[fetchedResultsController sections] count]); 
} 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    // Return the number of rows in the section. 
     id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section]; 

마지막으로 가져 오기 결과 컨트롤러에서 각 섹션의 양 텍스트를 설정합니다.

- (NSString *)controller:(NSFetchedResultsController *)controller sectionIndexTitleForSectionName:(NSString *)sectionName { 
     return sectionName; 
} 
관련 문제