Недавно я работаю над приложением.проект для iPhone (iOS).
Интересно, почему нет executeSelectorOnMainThread: в протоколе NSObject.
Мне нужно вызывать методы делегата в главном потоке, потому что они должны обрабатывать компоненты пользовательского интерфейса.
Вот пример, который я написал:
@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
Могу ли я запустить didFinishHandleWithResult: метод делегата для основного потока в классе MyOperation?
Поскольку здесь я реализую метод обработки пользовательского интерфейса каждыйраз я вызываю экземпляр MyOperation.Любое предложение будет полезно для меня.