如何解决为什么在NSObject协议中没有performSelectorOnMainThread :?
| 最近,我正在开发应用程序。 iPhone(iOS)项目。 我想知道为什么NSObject Protocol中没有performSelectorOnMainThread:。 我需要在主线程上调用委托的方法,因为它们必须处理UI组件。 这是我写的示例:@protocol MyOperationDelegate;
@interface MyOperation : NSOperation {
id <MyOperationDelegate> delegate;
}
@property (nonatomic,assign) id <MyOperationDelegate> delegate;
@end
@protocol MyOperationDelegate <NSObject>
@optional
- (void) didFinishHandleWithResult:(NSDictionary *)result;
@end
@implementation MyOperation
@synthesize delegate;
- (void) main {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *aDict = [[MySingleton sharedobject] fetchSomethingMeaningful];
//do something and call delegate
if ([delegate respondsToSelector:@selector(didFinishHandleWithResult:)]) {
[delegate performSelector:@selector(didFinishHandleWithResult:) withObject:
}
[pool release];
}
@end
@interface MyViewCon : UIViewController <MyOperationDelegate> {
NSOperationQueue *queue;
}
@end
@implementation MyViewCon
- (void) viewDidLoad {
MyOperation *op = [[MyOperation alloc] init];
op.delegate = self;
[queue addOperation:op];
[op release];
}
- (void) reloadUserInterface:(NSDictionary *)dict {
// Do reload data on User Interfaces.
}
- (void) didFinishHandleWithResult:(NSDictionary *)myDict {
// Couldn\'t execute method that\'s handling UI,maybe Could but very slow...
// So it must run on main thread.
[self performSelectorOnMainThread:@selector(reloadUserInterface:) withObject:myDict];
}
@end
我可以在MyOperation类的主线程上运行didFinishHandleWithResult:委托方法吗?
从这里开始,每次调用MyOperation实例时,我就实现UI处理方法。
任何建议对我都会有帮助。
解决方法
咱们试试吧:
dispatch_async(dispatch_get_main_queue(),^{
//your main thread code here
});
,NSObject
确实具有方法performSelectorOnMainThread:withObject:waitUntilDone
。您可以使用它。
,是的,您可以使用这种方法
[delegate performSelectorOnMainThread:@selector(reloadUserInterface:) withObject:myDict waitUntilDone:YES];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。