求和tableview ios中所有单元格的所有数字



我正在研究如何对表视图中的所有单元格求和。

用户装入板条箱的每个单元格的标签上都有一个编号。这个数字在每个单元格中是不同的。

如何求所有单元格中所有数字的和?

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

谢谢,希望有人能帮助我。可以自由询问任何其他细节。

编辑:

@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;

}

假设Year实体具有属性value,该属性是NSNumber:

NSArray *myNumbers = self.fetchedResultsController.fetchedObjects;
NSNumber *sum = [myNumbers valueForKeyPath:@"@sum.value"];

最新更新