1

Recently I'm working on app. project for iPhone(iOS).

I wonder why there isn't performSelectorOnMainThread: in NSObject Protocol.

I need to call to delegate's methods on main thread 'cause they have to handle UI components.

Here's sample I wrote:

@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

Can I run didFinishHandleWithResult: delegate method on main thread in MyOperation class?

Since here I am implementing UI handling method every time I call MyOperation instance. Any suggestion will be helpful for me.

Henry Kim
  • 21
  • 5
  • 1
    Self solved...;-). Using id delegate instead of id delegate then I could use performSelectorOnMainThread: on delegate receiver. – Henry Kim May 27 '11 at 01:27
  • possible duplicate of [Compiler gives warning on performSelectorOnMainThread:@selector(delegateMethod)](http://stackoverflow.com/questions/4499343/compiler-gives-warning-on-performselectoronmainthreadselectordelegatemethod) – JosephH Feb 22 '13 at 11:45

3 Answers3

1

Let's try:

dispatch_async(dispatch_get_main_queue(), ^{

        //your main thread code here

    });
Ghien cafe
  • 81
  • 3
0

NSObject does have a method performSelectorOnMainThread:withObject:waitUntilDone. You can use that.

Deepak Danduprolu
  • 44,595
  • 12
  • 101
  • 105
0

Yes you can make use of the method like this

[delegate performSelectorOnMainThread:@selector(reloadUserInterface:) withObject:myDict waitUntilDone:YES];
visakh7
  • 26,380
  • 8
  • 55
  • 69