ios – NSProgress奇怪的行为

前端之家收集整理的这篇文章主要介绍了ios – NSProgress奇怪的行为前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个由几个子任务组成的大任务.我想为这项重大任务添加进度报告.
为此,我想使用NSProgress,并根据类文档,我可以通过使用其子 – 父机制来做这种子任务进展.

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

  1. #define kFractionCompletedKeyPath @"fractionCompleted"
  2.  
  3. - (void)runBigTask {
  4. _progress = [NSProgress progressWithTotalUnitCount:100]; // 100 is arbitrary
  5.  
  6. [_progress addObserver:self
  7. forKeyPath:kFractionCompletedKeyPath
  8. options:NSKeyValueObservingOptionNew
  9. context:NULL];
  10.  
  11. [_progress becomeCurrentWithPendingUnitCount:100];
  12. [self subTask];
  13. [_progress resignCurrent];
  14. }
  15.  
  16. - (void)subTask {
  17. NSManagedObjectContext *parentContext = self.managedObjectContext; // self is AppDelegate in this example
  18. NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
  19. [bgContext setParentContext:parentContext];
  20.  
  21. [bgContext performBlockAndWait:^{
  22. NSInteger totalUnit = 1000;
  23. NSInteger completedUnits = 0;
  24. NSProgress *subProgress = [NSProgress progressWithTotalUnitCount:totalUnit];
  25.  
  26. for (int i=0; i < totalUnit; i++) {
  27.  
  28. // run some Core Data related code...
  29.  
  30. completedUnits++;
  31. subProgress.completedUnitCount = completedUnits;
  32. }
  33. }];
  34. }
  35.  
  36. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
  37. if ([keyPath isEqualToString:kFractionCompletedKeyPath]) {
  38. if ([object isKindOfClass:[NSProgress class]]) {
  39. NSProgress *progress = (NSProgress *)object;
  40. NSLog(@"progress… %f",progress.fractionCompleted);
  41. }
  42. } else {
  43. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  44. }
  45. }

如您所见,子任务使用背景上下文来运行一些与Core Data相关的代码,而后台上下文使用主上下文作为其父上下文.
这会导致进度的“fractionCompleted”属性出现一些奇怪的KVO.

这是印刷品:

  1. progress 1.000000 // why???
  2. progress 0.500000 // why?????
  3. progress 1.000000 // why???????
  4. progress 0.666650 // why???????????
  5. progress 0.666990
  6. progress 0.667320
  7. progress 0.667660
  8. progress 0.667990
  9. progress 0.668320
  10. ...
  11. progress 1.000000

如你所见,打印以1.0,0.5和1.0开始,然后是0.66?
从这里它正常,并像我期望的那样进入1.0.

我试图理解为什么会发生这种情况,我注意到如果我从背景上下文中删除父上下文,它工作正常!我从0.0升到1.0.

任何想法为什么会发生这种情况?我该如何解决这个问题?

添加了一个非常simple project以演示此问题(您可以删除setParentContext:调用以查看它没有它可以正常工作)

解决方法

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

这里发生的是当加载模型时,它正在读取一个plist文件.读取plist文件调用 – [NSData initWithContentsOfFile:],它在主线程上调用[NSProgress progressWithTotalUnitCount:].作为release notes point out,这将创建一个NSProgress,它是当前进步的孩子. initWithContentsOfFile:实际上正在执行此操作,并创建您创建的NSProgress的新子项:

  1. <NSProgress: 0x7f9353596f80> : Parent: 0x0 / Fraction completed: 0.0000 / Completed: 0 of 1
  2. <_NSProgressGroup: 0x7f935601a0d0> : Portion of parent: 100 Children: 1
  3. <NSProgress: 0x7f935600bf50> : Parent: 0x7f9353596f80 / Fraction completed: 0.0000 / Completed: 0 of 0

这里发生的事情是在你面前增加了额外的工作.此时,它对您要添加的其他工作一无所知. initWithContentsOfFile添加的子项:完成,从树中删除,然后开始添加您的工作.

当前进度从0开始,并且变为100%.您看到100%是因为您的KVO选项不包含NSKeyValueObservingOptionInitial.

NSData添加从0开始的子进度,并转到100%.

您的核心数据任务会添加一个从0开始并且(最终)达到100%的子项.

然而,这里的一个关键点是你正在使用performBlockAndWait:.虽然块本身在专用队列上运行,但此方法将阻止调用线程,这将延迟您的KVO通知. performBlockAndWait:如果可能的话,还将重用调用线程,这是需要注意的事情.

如果您编辑subTask方法以使用NSProgress包装自身作为整个工作单元的父级,最后重新调整当前状态,您可能会获得更接近您期望的行为:

  1. - (void)subTask {
  2. NSProgress *progress = [NSProgress progressWithTotalUnitCount:1];
  3. NSManagedObjectContext *parentContext = self.managedObjectContext;
  4. NSManagedObjectContext *bgContext = [[NSManagedObjectContext alloc]initWithConcurrencyType:NSPrivateQueueConcurrencyType];
  5. [bgContext setParentContext:parentContext];
  6.  
  7. [progress becomeCurrentWithPendingUnitCount:1];
  8. [bgContext performBlock:^{
  9.  
  10. ... stuff
  11.  
  12. [progress resignCurrent];
  13. }

NSProgress可能有点困难,但有了一些经验,它会变得更容易.我承诺!

猜你在找的iOS相关文章