3

我有这个观察者,我正在尝试以这种方式更新我的 UIProgressView:

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSProgress *progress = object;
NSLog(@"PROG: %f", progress.fractionCompleted);
[progressBar setProgress:_progressReceive.fractionCompleted animated:YES];

// Check which KVO key change has fired
if ([keyPath isEqualToString:kProgressCancelledKeyPath]) {
    // Notify the delegate that the progress was cancelled
    [progressBar removeFromSuperview];
    NSLog(@"CANCEL");

}
else if ([keyPath isEqualToString:kProgressCompletedUnitCountKeyPath]) {
    // Notify the delegate of our progress change

    if (progress.completedUnitCount == progress.totalUnitCount) {
        // Progress completed, notify delegate
        NSLog(@"COMPLETE");
        [progressBar removeFromSuperview];
    }
}
}

NSLog 正在显示数据:

...
2013-10-29 19:55:26.831 Cleverly[2816:6103] PROG: 0.243300
2013-10-29 19:55:26.835 Cleverly[2816:6103] PROG: 0.243340
2013-10-29 19:55:26.838 Cleverly[2816:6103] PROG: 0.243430
...

但是progressBar 没有更新。我注意到如果我使用 NSTimer 代替它会更新:

-(void)progressSend:(NSTimer*)timer{
NSLog(@"Fraction Complete: %@", [NSNumber numberWithDouble:progressSend.fractionCompleted]);
[progressBar setProgress:progressSend.fractionCompleted animated:YES];
}

为什么是这样??

4

2 回答 2

3
  1. 确保值正确
  2. 确保您的 KVO 在主线程上。
  3. 如果不是,则 dispatch_async 正在更改主队列上 UI 的代码块。
于 2013-10-29T19:06:50.370 回答
3

尝试在主线程上执行:

[self performSelectorOnMainThread:@selector(updateProgress:) withObject:[NSArray arrayWithObjects:progressBar, progress.fractionCompleted, nil] waitUntilDone:NO];

方法:

-(void) updateProgress:(NSArray*)array
{
    UIProgressView *progressBar = [array objectAtIndex:0];
    NSNumber *number = [array objectAtIndex:1];
    [progressBar setProgress:number.floatValue animated:YES];
}
于 2013-10-29T19:22:09.960 回答