gpt4 book ai didi

iOS NSNotificationCenter 奇怪的延迟

转载 作者:行者123 更新时间:2023-11-29 10:48:55 28 4
gpt4 key购买 nike

在我的应用程序中,我需要检测 ImagePicker 是否准备好拍照。我在这里找到了解决方案:How to know if iPhone camera is ready to take picture?

所以我在 viewDidLoad:

中得到了这段代码
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(showButton:)
name:AVCaptureSessionDidStartRunningNotification object:nil];

选择器看起来像这样:

- (void)showButton:(NSNotification *)notification{

NSLog(@"---CAMERA READY");

[button setHidden:NO];
[button setAlpha:0.0];
[button setTransform:CGAffineTransformScale(CGAffineTransformIdentity, 1.5, 1.5)];

[UIView animateWithDuration:.2 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
[button setAlpha:1.0];
[button setTransform:CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0)];
} completion:^(BOOL finished) {

}];

NSLog(@"---CAMERA READY");

}

这里发生了一些奇怪的事情,因为两个 NSLog 都会立即显示,但整个按钮动画甚至会在 30 秒后触发。

UIView 是否单独更新?如何同步日志和动画?

最佳答案

打算将其放入答案框中以供将来的用户查看..

您遇到的情况使您的通知看起来没有在主线程上被调用,并且在后台线程上更新 UI 是未定义的行为。解决这个问题的方法很简单,只需将方法的内容包装在 dispatch_async() 调用中并将所有内容发送回主队列即可。

- (void)showButton:(NSNotification *)notification {

dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"---CAMERA READY");

[button setHidden:NO];
[button setAlpha:0.0];
[button setTransform:CGAffineTransformScale(CGAffineTransformIdentity, 1.5, 1.5)];

[UIView animateWithDuration:.2 delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{
[button setAlpha:1.0];
[button setTransform:CGAffineTransformScale(CGAffineTransformIdentity, 1.0, 1.0)];
} completion:nil];

NSLog(@"---CAMERA READY");
});
}

作为替代方案,您可以只使用不同的 NSNotificationCenter 实例方法。具体来说,-addObserverForName:object:queue:usingBlock: 允许您指定应在哪个操作队列上执行回调 block 。在这种情况下,您需要传递 [NSOperationQueue mainQueue];

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSNotificationCenter_Class/Reference/Reference.html#//apple_ref/occ/instm/NSNotificationCenter/addObserverForName:object:queue:usingBlock :

NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];
self.localeChangeObserver = [center addObserverForName:NSCurrentLocaleDidChangeNotification object:nil
queue:mainQueue usingBlock:^(NSNotification *note) {

NSLog(@"The user's locale changed to: %@", [[NSLocale currentLocale] localeIdentifier]);
}];

关于iOS NSNotificationCenter 奇怪的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21281729/

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