我正在寻找如何在我的tableview中对所有单元格求和。
用户创建的每个单元格都在标签上有一个数字。每个单元格中的数字不同。
如何计算所有单元格中所有数字的总和?
我认为使用Core Data非常重要。
谢谢,希望有人能帮助我。 可以自由地询问任何其他细节。
编辑:
@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;
}
答案 0 :(得分:1)
假设Year
实体的属性value
是NSNumber
:
NSArray *myNumbers = self.fetchedResultsController.fetchedObjects;
NSNumber *sum = [myNumbers valueForKeyPath:@"@sum.value"];