草庐IT

ios - 更改无法识别我附加到后台线程的 NSFetchedResultsController

coder 2024-01-24 原文

我正在使用 MagicalRecord,但不确定这是 MagicalRecord 还是 CoreData 中的错误。

当用户单击新按钮并将其保存到默认上下文时,我在我的 UI 线程中创建新实体:

- (IBAction) saveToCoreData:(UIButton *)sender {
    NSManagedObjectContext *context = [NSManagedObjectContext MR_defaultContext];
    Report *report = [Report MR_createInContext:context];
    report.dirty = [NSNumber numberWithBool:YES];
    report.timestamp = [NSDate date];

    Document *document = [Document MR_createInContext:context];
    document.dirty = [NSNumber numberWithBool:YES];
    document.timestamp = [NSDate date];
    document.report = report;

    NSLog(@"Saving.................................");
    [context MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        NSLog(@"Saved report and document to PS");
    }];
}

注意我有一个附有子文档的报告实体

然后我有一个后台线程,它只负责监听变化,如果 Report 发生变化,dirty == YES 然后它需要提交给服务器。

我在后台线程上设置了一个 NSFetchedResultsController 来监听变化,所以我知道什么时候保存到服务器。

// This should get me a new background context, use it in FRC below
    self.fetchedResultsController = [Report MR_fetchAllSortedBy:@"timestamp"
                                                      ascending:NO
                                                  withPredicate:[NSPredicate predicateWithFormat:@"dirty == YES"]
                                                        groupBy:nil
                                                       delegate:self
                                                      inContext:_managedObjectContext];

然后我实现监听变化的方法:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id) anObject atIndexPath:(NSIndexPath *) indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *) newIndexPath {
    switch(type) {

        case NSFetchedResultsChangeInsert:
            NSLog(@"report inserted");
            [self pushReport:anObject];
            break;
        case NSFetchedResultsChangeUpdate:
            NSLog(@"report updated");
            [self pushReport:anObject];
            break;
    }
}

并将其推送到服务器:

- (void) pushReport:(Report *) report {
    __weak ReportPushService *weakSelf = self;
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:@"http://echo.jsontest.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [weakSelf.managedObjectContext performBlockAndWait:^{
            report.remoteId = @"12345"; // fake id from server
            report.dirty = [NSNumber numberWithBool:NO];

            [weakSelf.managedObjectContext MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
                NSLog(@"Saved server info to Report");
            }];
        }];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         NSLog(@"Error: %@", error);
     }];
}

FRC 的工作就像一个魅力,当 UI 线程添加一个带有 dirty == YES 的新报告时,FRC 将其拾取并提交给服务器。

这是我遇到问题的地方。将报告保存到服务器后,服务器会返回该报告的 ID。我将其设置为 report.remoteId。

我在另一个类中有一个FRC,负责将文档保存到服务器。它将检查文件是否脏 == YES 以及它的父级(报告)remoteId != nil,即:

    self.fetchedResultsController = [Document MR_fetchAllSortedBy:@"timestamp"
                                                      ascending:NO
                                                  withPredicate:[NSPredicate predicateWithFormat:@"report.remoteId != nil && dirty == YES"]
                                                        groupBy:nil
                                                       delegate:self
                                                      inContext:_managedObjectContext];

它使用与报表“推送”类中的 FRC Controller 相同的后台 MOC。

然后我监听那个 FRC 的变化:

- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id) anObject atIndexPath:(NSIndexPath *) indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *) newIndexPath {
    switch(type) {
        case NSFetchedResultsChangeInsert:
            NSLog(@"document inserted");
            [self pushDocument:anObject];
            break;
        case NSFetchedResultsChangeUpdate:
            NSLog(@"document updated");
            [self pushDocument:anObject];
            break;
    }
}

但是他的 FRC 从未看到任何变化,即使我已经验证我有一个带有 remoteId 的报告!= nil 和一个(子)文档带有 dirty == YES。

为什么 Documents FRC 看不到与该谓词匹配的对象?

最佳答案

FRC 的问题/限制是它只包含为其设置的实体。在这种情况下:

self.fetchedResultsController = [Document MR_fetchAllSortedBy:@"timestamp"
                                                      ascending:NO
                                                  withPredicate:[NSPredicate predicateWithFormat:@"report.remoteId != nil && dirty == YES"]
                                                        groupBy:nil
                                                       delegate:self
                                                      inContext:_managedObjectContext];

FRC 将只包含文档实体。初始提取将作用于报告关系。但是,如果报告发生更改,即使谓词匹配,FRC 也不会更新。

http://www.mlsite.net/blog/?p=825

这里

Changing a managed object property doesn't trigger NSFetchedResultsController to update the table view

关于ios - 更改无法识别我附加到后台线程的 NSFetchedResultsController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27517396/

有关ios - 更改无法识别我附加到后台线程的 NSFetchedResultsController的更多相关文章

  1. ruby-on-rails - Ruby on Rails 迁移,将表更改为 MyISAM - 2

    如何正确创建Rails迁移,以便将表更改为MySQL中的MyISAM?目前是InnoDB。运行原始执行语句会更改表,但它不会更新db/schema.rb,因此当在测试环境中重新创建表时,它会返回到InnoDB并且我的全文搜索失败。我如何着手更改/添加迁移,以便将现有表修改为MyISAM并更新schema.rb,以便我的数据库和相应的测试数据库得到相应更新? 最佳答案 我没有找到执行此操作的好方法。您可以像有人建议的那样更改您的schema.rb,然后运行:rakedb:schema:load,但是,这将覆盖您的数据。我的做法是(假设

  2. ruby-on-rails - 由于 "wkhtmltopdf",PDFKIT 显然无法正常工作 - 2

    我在从html页面生成PDF时遇到问题。我正在使用PDFkit。在安装它的过程中,我注意到我需要wkhtmltopdf。所以我也安装了它。我做了PDFkit的文档所说的一切......现在我在尝试加载PDF时遇到了这个错误。这里是错误:commandfailed:"/usr/local/bin/wkhtmltopdf""--margin-right""0.75in""--page-size""Letter""--margin-top""0.75in""--margin-bottom""0.75in""--encoding""UTF-8""--margin-left""0.75in""-

  3. ruby-on-rails - 无法使用 Rails 3.2 创建插件? - 2

    我对最新版本的Rails有疑问。我创建了一个新应用程序(railsnewMyProject),但我没有脚本/生成,只有脚本/rails,当我输入ruby./script/railsgeneratepluginmy_plugin"Couldnotfindgeneratorplugin.".你知道如何生成插件模板吗?没有这个命令可以创建插件吗?PS:我正在使用Rails3.2.1和ruby​​1.8.7[universal-darwin11.0] 最佳答案 随着Rails3.2.0的发布,插件生成器已经被移除。查看变更日志here.现在

  4. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  5. ruby-on-rails - 无法在centos上安装therubyracer(V8和GCC出错) - 2

    我正在尝试在我的centos服务器上安装therubyracer,但遇到了麻烦。$geminstalltherubyracerBuildingnativeextensions.Thiscouldtakeawhile...ERROR:Errorinstallingtherubyracer:ERROR:Failedtobuildgemnativeextension./usr/local/rvm/rubies/ruby-1.9.3-p125/bin/rubyextconf.rbcheckingformain()in-lpthread...yescheckingforv8.h...no***e

  6. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  7. ruby-on-rails - 项目升级后 Pow 不会更改 ruby​​ 版本 - 2

    我在我的Rails项目中使用Pow和powifygem。现在我尝试升级我的ruby​​版本(从1.9.3到2.0.0,我使用RVM)当我切换ruby​​版本、安装所有gem依赖项时,我通过运行railss并访问localhost:3000确保该应用程序正常运行以前,我通过使用pow访问http://my_app.dev来浏览我的应用程序。升级后,由于错误Bundler::RubyVersionMismatch:YourRubyversionis1.9.3,butyourGemfilespecified2.0.0,此url不起作用我尝试过的:重新创建pow应用程序重启pow服务器更新战俘

  8. ruby - Capistrano 3 在任务中更改 ssh_options - 2

    我尝试使用不同的ssh_options在同一阶段运行capistranov.3任务。我的production.rb说:set:stage,:productionset:user,'deploy'set:ssh_options,{user:'deploy'}通过此配置,capistrano与用户deploy连接,这对于其余的任务是正确的。但是我需要将它连接到服务器中配置良好的an_other_user以完成一项特定任务。然后我的食谱说:...taskswithoriginaluser...task:my_task_with_an_other_userdoset:user,'an_othe

  9. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  10. ruby - 无法覆盖 irb 中的 to_s - 2

    我在pry中定义了一个函数:to_s,但我无法调用它。这个方法去哪里了,怎么调用?pry(main)>defto_spry(main)*'hello'pry(main)*endpry(main)>to_s=>"main"我的ruby版本是2.1.2看了一些答案和搜索后,我认为我得到了正确的答案:这个方法用在什么地方?在irb或pry中定义方法时,会转到Object.instance_methods[1]pry(main)>defto_s[1]pry(main)*'hello'[1]pry(main)*end=>:to_s[2]pry(main)>defhello[2]pry(main)

随机推荐