1

我正在寻找如何汇总我的表格视图中的所有单元格。

用户创建的每个单元格的标签上都有一个数字。这个数字在每个单元格中是不同的。

如何计算所有单元格中所有数字的总和?

我认为说我使用核心数据很重要。

谢谢,希望有人能帮助我。随意询问任何其他细节。

编辑:

@synthesize fetchedResultsController = __fetchedResultsController;
@synthesize managedObjectContext = __managedObjectContext;
@synthesize selectedYear;


- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"fondo.png"]];

    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    [self.tableView setSeparatorColor:[UIColor brownColor]];
}


- (void)setupFetchedResultsController
{
    // 1 - Decide what Entity you want
    NSString *entityName = @"Years"; // Put your entity name here
    NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);

    // 2 - Request that Entity
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];

    // 3 - Filter it if you want
    //request.predicate = [NSPredicate predicateWithFormat:@"Years.name = Blah"];

    // 4 - Sort it if you want
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"subject"
                                                                                     ascending:YES
                                                                                      selector:@selector(localizedCaseInsensitiveCompare:)]];
    // 5 - Fetch it
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                        managedObjectContext:self.managedObjectContext
                                                                          sectionNameKeyPath:nil
                                                                                   cacheName:nil];
    [self performFetch];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupFetchedResultsController];

}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"My Cell";

    MarksCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[MarksCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }

    Year *years = [self.fetchedResultsController objectAtIndexPath:indexPath];
    cell.celltitlelabel.text = years.subject;


    return cell;


}
4

1 回答 1

1

假设Year实体有一个属性valueNSNumber

NSArray *myNumbers = self.fetchedResultsController.fetchedObjects;
NSNumber *sum = [myNumbers valueForKeyPath:@"@sum.value"];
于 2013-06-26T21:39:46.203 回答