为什么我会收到“wait_fences:未能收到回复”这段代码?这是我使用通知回传给主线程的方式吗?
#import "ViewController.h"
@implementation ViewController
@synthesize alert;
#pragma mark - Background Thread Test Methods
- (void) ConfigTasksForBackground:(id)sender{
NSLog(@"ConfigTasksForBackground - Starting");
[NSThread sleepForTimeInterval:6];
[[NSNotificationCenter defaultCenter] postNotificationName:@"ModelChanged" object:self];
NSLog(@"ConfigTasksForBackground - Ending");
}
#pragma mark - Callbacks
- (void) ModelChangedHandler:(NSNotification *) notification {
if ([[notification name] isEqualToString:@"ModelChanged"]) {
NSLog(@"ModelChangedHandler");
[self.alert dismissWithClickedButtonIndex:0 animated:false];
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(ModelChangedHandler:)
name:@"ModelChanged"
object:nil];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
self.alert = [[[UIAlertView alloc] initWithTitle:@"Title"
message:@"viewDidAppear"
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:nil] autorelease];
[alert show];
[self performSelectorInBackground:@selector(ConfigTasksForBackground:) withObject:nil];
}
@end
输出是:
2011-11-07 15:15:42.730 test_background[6876:13603] ConfigTasksForBackground - Starting
2011-11-07 15:15:48.734 test_background[6876:13603] ModelChangedHandler
2011-11-07 15:15:49.236 test_background[6876:13603] ConfigTasksForBackground - Ending
wait_fences: failed to receive reply: 10004003
答案 0 :(得分:3)
这里有一个明显的问题。您正在从后台线程发布通知(这很好),这意味着在后台线程上调用通知处理程序ModelChangedHandler
。然后处理程序解除必须在主线程上完成的警报视图。尝试将代码更改为:
- (void) ModelChangedHandler:(NSNotification *) notification {
if (![NSThread isMainThread]) {
[self performSelectorOnMainThread:@selector(ModelChangedHandler:) withObject:notification waitUntilDone:NO];
}
else if ([[notification name] isEqualToString:@"ModelChanged"]) {
NSLog(@"ModelChangedHandler");
[self.alert dismissWithClickedButtonIndex:0 animated:false];
}
}
编辑:输入太快,更改了答案以反映正确的UI对象。
答案 1 :(得分:2)
以下是摆脱wait_fences错误的方法。更改解除alertView的行以使用动画,如下所示:
[self.alert dismissWithClickedButtonIndex:0 animated:YES];
我认为wait_fences与具有警报视图的视图动画状态有关,但很难确定。我认为这应该消除错误消息。我的另一个答案没有直接摆脱错误,但我仍然推荐它。 UI操作应该在主线程上完成。