我正在向窗口添加UIView,同时发生一些线程后台更新,然后使用委托方法删除视图。一切都按预期发生,但在调用hideActivityViewer后,视图仍会持续几秒钟。不确定是否重要,但应用程序使用UITabBarController。
更新方法位于一个单独的类中,但目前在AppDelegate.m中用于调试目的。正如我所说,一切正常。更新完成后,它会将“Foo”写入日志,但视图会持续几秒钟。任何帮助,将不胜感激。多余的代码已被省略:
AppDelegate.h
@interface AppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
UIWindow *window;
UITabBarController *tabBarController;
UIView *activityView;
id _delegate;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) UITabBarController *tabBarController;
- (void)showActivityViewer;
- (void)updateComplete;
- (void)updateRemoteDataThreadedWithDelegate:(id)aDelegate;
- (id)delegate;
- (void)setDelegate:(id)new_delegate;
@end
AppDelegate.m
- (void)updateRemoteDataThreadedWithDelegate:(id)aDelegate {
[self setDelegate:aDelegate];
NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(updateRemoteDataWithDelegate:) object:aDelegate];
[queue addOperation:operation];
[operation release];
}
- (void)updateRemoteDataWithDelegate:(id)aDelegate {
[self setDelegate:aDelegate];
...do stuff...
if ([_delegate respondsToSelector:@selector(updateComplete)]) {
[_delegate updateComplete];
} else {
[NSException raise:NSInternalInconsistencyException format:@"Delegate doesn't respond to updateComplete"];
}
}
-(void)showActivityViewer {
[activityView release];
activityView = [[UIView alloc] initWithFrame: CGRectMake(window.bounds.size.width-50, 60, 50, 50)];
...formatting...
[window addSubview: activityView];
[activityView release];
}
-(void)hideActivityViewer {
[activityView removeFromSuperview];
activityView = nil;
NSLog(@"Foo");
}
- (id)delegate {
return _delegate;
}
- (void)setDelegate:(id)new_delegate {
_delegate = new_delegate;
}
答案 0 :(得分:3)
在我看来,你正在使一个线程调用一个在UIView中执行操作的委托方法 - 你不能这样做,因为UIView不是线程安全的。
使用performSelectorOnMainThread安全地执行此操作 - 您的委托方法可以通过这种方式调用主线程上的另一个方法。
答案 1 :(得分:3)
UI操作应该在主线程上完成;你的例子将UIView推送到一个单独的线程,不建议这样做。