NSProgress的奇怪行为

9
我有一个大任务,包含几个子任务。我想为这个大任务添加进度报告。
为此,我想使用NSProgress,根据类文档,我可以通过使用其子父机制来完成这种子任务进度。

因此,为了简化它,假设我有一个由一个子任务组成的大任务(当然,在现实生活中会有更多的子任务)。所以这是我所做的:

#define kFractionCompletedKeyPath @"fractionCompleted"  

- (void)runBigTask {
    _progress = [NSProgress progressWithTotalUnitCount:100]; // 100 is arbitrary 

    [_progress addObserver:self
                forKeyPath:kFractionCompletedKeyPath
                   options:NSKeyValueObservingOptionNew
                   context:NULL];

    [_progress becomeCurrentWithPendingUnitCount:100]; 
    [self subTask];
    [_progress resignCurrent];
} 

- (void)subTask {
    NSManagedObjectContext *parentContext = self.managedObjectContext; // self is AppDelegate in this example
    NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [bgContext setParentContext:parentContext];

    [bgContext performBlockAndWait:^{
        NSInteger totalUnit = 1000;
        NSInteger completedUnits = 0;
        NSProgress *subProgress = [NSProgress progressWithTotalUnitCount:totalUnit];

        for (int i=0; i < totalUnit; i++) {   

            // run some Core Data related code...  

            completedUnits++;
            subProgress.completedUnitCount = completedUnits;
        }
    }];
}      

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if ([keyPath isEqualToString:kFractionCompletedKeyPath]) {
        if ([object isKindOfClass:[NSProgress class]]) {
            NSProgress *progress = (NSProgress *)object;
            NSLog(@"progress… %f", progress.fractionCompleted);
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

正如您所看到的,子任务使用背景上下文来运行一些与Core Data相关的代码,而背景上下文将主上下文作为其父上下文。
这会导致进度条的“fractionCompleted”属性出现一些奇怪的KVO现象。
这是打印输出:
progress… 1.000000 // why???
progress… 0.500000 // why?????
progress… 1.000000 // why???????
progress… 0.666650 // why???????????
progress… 0.666990
progress… 0.667320
progress… 0.667660
progress… 0.667990
progress… 0.668320
...  
progress… 1.000000  

正如您所看到的,打印从1.0、0.5和1.0开始,然后到了0.66?!从这里开始,它表现得很正常,并像我预期的那样变成了1.0。

我试图理解为什么会发生这种情况,我注意到如果我从背景上下文中删除父上下文,它就能正常工作!我获得了从0.0到1.0的进度。

有任何想法为什么会发生这种情况?以及我该如何修复它?

我添加了一个非常简单的项目simple project来演示这个问题(您可以删除setParentContext:调用,以查看它在没有此调用的情况下运行良好)。


NSProgress的最佳文档在这里:https://developer.apple.com/library/mac/releasenotes/Foundation/RN-Foundation/ - quellish
2个回答

5
当发生这种情况时,堆栈跟踪如下所示:
(lldb) bt
* thread #1: tid = 0x81f2, 0x0000000105bffcda Foundation`-[NSProgress setTotalUnitCount:], queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
  * frame #0: 0x0000000105bffcda Foundation`-[NSProgress setTotalUnitCount:]
    frame #1: 0x0000000105bfeb1b Foundation`+[NSProgress progressWithTotalUnitCount:] + 87
    frame #2: 0x0000000105a31213 Foundation`_NSReadBytesFromFileWithExtendedAttributes + 287
    frame #3: 0x0000000105a3109d Foundation`-[NSData(NSData) initWithContentsOfFile:] + 89
    frame #4: 0x0000000105a30b40 Foundation`+[NSDictionary(NSDictionary) newWithContentsOf:immutable:] + 101
    frame #5: 0x0000000105a5622a Foundation`+[NSDictionary(NSDictionary) dictionaryWithContentsOfFile:] + 45
    frame #6: 0x00000001043c4560 CoreData`-[NSManagedObjectModelBundle initWithPath:] + 224
    frame #7: 0x00000001043c42ed CoreData`-[NSManagedObjectModel initWithContentsOfURL:] + 205
    frame #8: 0x00000001040f723f CDProgress`-[AppDelegate managedObjectModel](self=0x00007fbe48c21f90, _cmd=0x000000010459b37b) + 223 at AppDelegate.m:127
    frame #9: 0x00000001040f7384 CDProgress`-[AppDelegate persistentStoreCoordinator](self=0x00007fbe48c21f90, _cmd=0x000000010459c1cb) + 228 at AppDelegate.m:142
    frame #10: 0x00000001040f708c CDProgress`-[AppDelegate managedObjectContext](self=0x00007fbe48c21f90, _cmd=0x0000000104598f0d) + 92 at AppDelegate.m:111
    frame #11: 0x00000001040f6bdb CDProgress`-[AppDelegate subTask](self=0x00007fbe48c21f90, _cmd=0x00000001040f7997) + 43 at AppDelegate.m:45
    frame #12: 0x00000001040f6b89 CDProgress`-[AppDelegate runTask](self=0x00007fbe48c21f90, _cmd=0x00000001040f7928) + 233 at AppDelegate.m:40
    frame #13: 0x00000001040f6a4b CDProgress`-[AppDelegate application:didFinishLaunchingWithOptions:](self=0x00007fbe48c21f90, _cmd=0x0000000104f5dba9, application=0x00007fbe48f00fb0, launchOptions=0x0000000000000000) + 571 at AppDelegate.m:26
    frame #14: 0x000000010477c5a5 UIKit`-[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 234
    frame #15: 0x000000010477d0ec UIKit`-[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 2463
    frame #16: 0x000000010477fe5c UIKit`-[UIApplication _runWithMainScene:transitionContext:completion:] + 1350
    frame #17: 0x000000010477ed22 UIKit`-[UIApplication workspaceDidEndTransaction:] + 179
    frame #18: 0x00000001088092a3 FrontBoardServices`__31-[FBSSerialQueue performAsync:]_block_invoke + 16
    frame #19: 0x000000010615fabc CoreFoundation`__CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    frame #20: 0x0000000106155805 CoreFoundation`__CFRunLoopDoBlocks + 341
    frame #21: 0x00000001061555c5 CoreFoundation`__CFRunLoopRun + 2389
    frame #22: 0x0000000106154a06 CoreFoundation`CFRunLoopRunSpecific + 470
    frame #23: 0x000000010477e799 UIKit`-[UIApplication _run] + 413
    frame #24: 0x0000000104781550 UIKit`UIApplicationMain + 1282
    frame #25: 0x00000001040f7793 CDProgress`main(argc=1, argv=0x00007fff5bb09308) + 115 at main.m:16
    frame #26: 0x000000010686f145 libdyld.dylib`start + 1
(lldb) 

这里发生的是,当模型被加载时,它会读取一个plist文件。读取plist文件会调用-[NSData initWithContentsOfFile:],从而在主线程上调用+[NSProgress progressWithTotalUnitCount:]。正如发布说明所指出的那样,这将创建一个作为当前进度子级的NSProgress。实际上,initWithContentsOfFile:正在执行此操作,并创建了一个新的NSProgress子级,该子级是您创建的NSProgress的子级:
<NSProgress: 0x7f9353596f80> : Parent: 0x0 / Fraction completed: 0.0000 / Completed: 0 of 1  
   <_NSProgressGroup: 0x7f935601a0d0> : Portion of parent: 100 Children: 1
      <NSProgress: 0x7f935600bf50> : Parent: 0x7f9353596f80 / Fraction completed: 0.0000 / Completed: 0 of 0 

这里发生的是在你之前添加了额外的工作。此时,它不知道你即将添加的额外工作。由initWithContentsOfFile:添加的子项完成后,会从树中删除,然后你开始添加你的工作。
当前进度从0开始,到100%结束。因为你的KVO选项不包括NSKeyValueObservingOptionInitial,所以你看到了100%。 NSData添加了一个子进度,从0开始,到100%结束。
你的Core Data任务添加了一个从0开始(最终)到100%结束的子项。
然而,这里的一个关键点是你正在使用performBlockAndWait:。虽然块本身在私有队列上运行,但此方法将阻塞调用线程,这将延迟你的KVO通知。performBlockAndWait:还会尽可能地重用调用线程,这是需要注意的一点。
如果你编辑你的subTask方法,用NSProgress包装自己作为整个工作单元的父项,并在结束时退出当前项,你可能会得到更接近你预期的行为:
- (void)subTask {
    NSProgress  *progress   = [NSProgress progressWithTotalUnitCount:1];
    NSManagedObjectContext *parentContext = self.managedObjectContext;
    NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [bgContext setParentContext:parentContext];

    [progress becomeCurrentWithPendingUnitCount:1];
    [bgContext performBlock:^{

    ... stuff

    [progress resignCurrent];
}

NSProgress可能有点难以理解,但通过一些经验,它会变得更容易。我保证!


2
另外,作为一则附注,我会将此归档为一个错误。最坏的情况是他们告诉你它是按照预期工作的。 - quellish

1
[NSManagedObjectModel initWithContentsOfURL:]中似乎必须有一个NSProgress计数器。在进入[self subTask]之前,您需要设置自己以接收任何进度指示器的通知(通过将_progress设置为当前并注册自己以观察更改)。然后,在该例程内部,您调用惰性获取器self.managedObjectContext,它又调用[NSManagedObjectModel initWithContentsOfURL:],这显然具有2个单位的进度计数器。看来您需要非常小心地放置对[NSProgress becomeCurrentWithPendingUnitCount:][NSProgress resignCurrent]的调用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接