gpt4 book ai didi

iOS,核心数据 : Sum of subcategories value not ready on viewdidload and not updated thereafter

转载 作者:行者123 更新时间:2023-11-29 03:27:29 37 4
gpt4 key购买 nike

我有一个基本的数据模型。一个主要类别有几个子类别。在每个子类别中,您定义每年预算的金额。所以我想:

a) 每个主要类别的所有子类别支出的总和。b) 所有主要类别支出的总和作为总预算

但是目前这不起作用。我在 viewwillappear 方法中设置了文本字段(因为我一直希望在再次打开 View 时更新它)。首先加载总和为 0。切换到另一个 View 并返回后,显示正确的总和。之后它不会自行更新。这是为什么?

我是 Coredata 的新手。与我在这里执行的查询相比,获取的属性可能是更好的方法吗?以下是相关的代码部分:

我的主视图 Controller (这里显示所有主要类别的总预算):

- (void)viewWillAppear:(BOOL)animated
{
//Initialize database
[super viewWillAppear:animated];
if(!self.budgetDatabase){
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentationDirectory inDomains:NSUserDomainMask] lastObject];
[url URLByAppendingPathComponent:@"BudgetDatabase"];
self.budgetDatabase = [[UIManagedDocument alloc]initWithFileURL:url];
}

//Total cost/month will be fetched and formatted
NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

self.sumLabel.text = [[DatabaseFetches budgetPerMonthForManagedObjectContext:self.budgetDatabase.managedObjectContext] getLocalizedCurrencyString];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

数据库获取:

+ (NSNumber *)budgetPerMonthForManagedObjectContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MainCategory"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"position" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];

NSArray *matches = [context executeFetchRequest:request error:nil];
CostsPeriodically *totalCostPerMonth = [[CostsPeriodically alloc]init];

for (MainCategory *mainCategory in matches) {
for (SpendingCategory *category in mainCategory.hasSpendingCategories){
[totalCostPerMonth addCosts:category.costPerYear];
}
}

return totalCostPerMonth.sumPerMonth;
}

编辑:这些是完整的 Fetched Results Controller 设置方法:

- (void)setupFetchedResultsController
{
NSError *error = nil;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"MainCategory"];
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"position" ascending:YES]];
[self.budgetDatabase.managedObjectContext executeFetchRequest:request error:&error];

self.fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:request
managedObjectContext:self.budgetDatabase.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
}

-(void)useDocument
{
if(![[NSFileManager defaultManager]fileExistsAtPath:[self.budgetDatabase.fileURL path]]){
[self.budgetDatabase saveToURL:self.budgetDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
[self setupFetchedResultsController];
//[self initializeDatabaseWithData];
}];
} else if (self.budgetDatabase.documentState == UIDocumentStateClosed){
[self.budgetDatabase openWithCompletionHandler:^(BOOL success){
[self setupFetchedResultsController];
}];
} else if (self.budgetDatabase.documentState == UIDocumentStateNormal){
[self setupFetchedResultsController];
}
}

-(void)setBudgetDatabase:(UIManagedDocument *)budgetDatabase
{
if(_budgetDatabase != budgetDatabase){
_budgetDatabase = budgetDatabase;
[self useDocument];
}
}

进一步编辑,整个 Fetched results Controller 类:

@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize suspendAutomaticTrackingOfChangesInManagedObjectContext = _suspendAutomaticTrackingOfChangesInManagedObjectContext;
@synthesize debug = _debug;
@synthesize beganUpdates = _beganUpdates;
@synthesize reordering = _reordering;
@synthesize tableView = _tableView;

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}

#pragma mark - Fetching

- (void)performFetch
{
if (self.fetchedResultsController) {
if (self.fetchedResultsController.fetchRequest.predicate) {
if (self.debug) NSLog(@"[%@ %@] fetching %@ with predicate: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName, self.fetchedResultsController.fetchRequest.predicate);
} else {
if (self.debug) NSLog(@"[%@ %@] fetching all %@ (i.e., no predicate)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName);
}
NSError *error;
[self.fetchedResultsController performFetch:&error];
if (error) NSLog(@"[%@ %@] %@ (%@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), [error localizedDescription], [error localizedFailureReason]);
} else {
if (self.debug) NSLog(@"[%@ %@] no NSFetchedResultsController (yet?)", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
}
[self.tableView reloadData];
}

- (void)setFetchedResultsController:(NSFetchedResultsController *)newfrc
{
NSFetchedResultsController *oldfrc = _fetchedResultsController;
if (newfrc != oldfrc) {
_fetchedResultsController = newfrc;
newfrc.delegate = self;
if ((!self.title || [self.title isEqualToString:oldfrc.fetchRequest.entity.name]) && (!self.navigationController || !self.navigationItem.title)) {
self.title = newfrc.fetchRequest.entity.name;
}
if (newfrc) {
if (self.debug) NSLog(@"[%@ %@] %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), oldfrc ? @"updated" : @"set");
[self performFetch];
} else {
if (self.debug) NSLog(@"[%@ %@] reset to nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
[self.tableView reloadData];
}
}
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.fetchedResultsController sections] count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[[self.fetchedResultsController sections] objectAtIndex:section] name];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}

- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [self.fetchedResultsController sectionIndexTitles];
}

#pragma mark - NSFetchedResultsControllerDelegate

- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
if(!self.reordering){
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext) {
[self.tableView beginUpdates];
self.beganUpdates = YES;
}
}
}

- (void)controller:(NSFetchedResultsController *)controller
didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex
forChangeType:(NSFetchedResultsChangeType)type
{
if(!self.reordering){
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext)
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;

case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
}


- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
if(!self.reordering){
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext)
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;

case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;

case NSFetchedResultsChangeUpdate:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;

case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
}

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if(!self.reordering){
if (self.beganUpdates) [self.tableView endUpdates];
}
}

- (void)endSuspensionOfUpdatesDueToContextChanges
{
_suspendAutomaticTrackingOfChangesInManagedObjectContext = NO;
}

- (void)setSuspendAutomaticTrackingOfChangesInManagedObjectContext:(BOOL)suspend
{
if (suspend) {
_suspendAutomaticTrackingOfChangesInManagedObjectContext = YES;
} else {
[self performSelector:@selector(endSuspensionOfUpdatesDueToContextChanges) withObject:0 afterDelay:0];
}
}

最佳答案

我认为问题在于,您只是在 UIManagedDocument 打开(异步)之前直接更新 viewWillAppear 中的 UI。因此,您需要在 OpenWithCompletionHandler 中有一个回调来更新您的 UI。创建一个类似于

的方法
- (void)displayData {
//Total cost/month will be fetched and formatted
NSNumberFormatter *numberFormatter =[[NSNumberFormatter alloc] init];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

self.sumLabel.text = [[DatabaseFetches budgetPerMonthForManagedObjectContext:self.budgetDatabase.managedObjectContext] getLocalizedCurrencyString];
[self.tableView deselectRowAtIndexPath:[self.tableView indexPathForSelectedRow] animated:YES];
}

并从completionHandlers中调用它

-(void)useDocument
{
if(![[NSFileManager defaultManager]fileExistsAtPath:[self.budgetDatabase.fileURL path]]){
[self.budgetDatabase saveToURL:self.budgetDatabase.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
[self setupFetchedResultsController];
[self displayData]; ******
//[self initializeDatabaseWithData];
}];
} else if (self.budgetDatabase.documentState == UIDocumentStateClosed){
[self.budgetDatabase openWithCompletionHandler:^(BOOL success){
[self setupFetchedResultsController];
[self displayData]; ******
}];
} else if (self.budgetDatabase.documentState == UIDocumentStateNormal){
[self setupFetchedResultsController];
[self displayData]; ******
}
}

关于iOS,核心数据 : Sum of subcategories value not ready on viewdidload and not updated thereafter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20274249/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com