为什么没有performSelectorOnMainThread:在NSObject协议中?

时间:2011-05-26 06:21:25

标签: iphone ios ios4 nsthread nsoperation

最近我正在开发app。适用于iPhone(iOS)的项目。

我想知道为什么没有performSelectorOnMainThread:在NSObject Protocol中。

我需要在主线程上调用委托的方法,因为它们必须处理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:delegate方法吗?

因为我每次调用MyOperation实例时都会实现UI处理方法。 任何建议对我都有帮助。

3 个答案:

答案 0 :(得分:1)

让我们试试:

dispatch_async(dispatch_get_main_queue(), ^{

        //your main thread code here

    });

答案 1 :(得分:0)

NSObject确实有方法performSelectorOnMainThread:withObject:waitUntilDone。你可以使用它。

答案 2 :(得分:0)

是的,你可以使用像这样的方法

[delegate performSelectorOnMainThread:@selector(reloadUserInterface:) withObject:myDict waitUntilDone:YES];