Compiler gives warning on performSelectorOnMainThread:@selector(delegateMethod)

后端 未结 4 2053
渐次进展
渐次进展 2021-01-05 02:29

I have an NSOperation that wraps some web service functionality. The NSOperation has a delegate that is to be messaged when the operation is over.

As the NSOperation

相关标签:
4条回答
  • 2021-01-05 02:31

    Actually on iOS 4 I prefer using NSNotifications and Observers (with Blocks) to perform updates on the mainthread.

    - (id)addObserverForName:(NSString *)name object:(id)obj queue:(NSOperationQueue *)queue usingBlock:(void (^)(NSNotification *))block
    

    I wrote down my design here.

    0 讨论(0)
  • 2021-01-05 02:38

    performSelectorOnMainThread:withObject:waitUntilDone: method is declared in NSObject class. If your delegate object inherits from NSObject you can declare it as

    NSObject<MyDelegateProtocol> *delegate;
    

    So compiler will know that delegate responds to NSObject's methods and won't issue a warning.

    0 讨论(0)
  • 2021-01-05 02:45

    1) Declare your delegate's protocol to extend the NSObject protocol in the .h file

    @protocol YourDelegateProtocol <NSObject>
    

    2) Cast to NSObject in your call

    [(NSObject*)delegate performSelectorOnMainThread:@selector(getDealersIDSuccess:) withObject:result waitUntilDone:YES];
    

    I definitely recommend number (1).

    0 讨论(0)
  • 2021-01-05 02:53

    It might be even a better solution not call performSelectorOnMainThread: on a delegate or other protocol implementation. Make it the responsibility of the delegate/receiver to determine if it needs to do things on the main thread.

    [delegate performSelector:@selector(delegateAction:)
                   withObject:actionData];
    

    Delegate implementation

    - (void)delegateAction:(NSData*)actionData
    {
        [self performSelectorOnMainThread:@selector(updateUIForAction:)
                               withObject:actionData
                            waitUntilDone:NO];
    }
    
    - (void)updateUIForAction:(NSData*)actionData
    {
        // Update your UI objects here
    }
    

    It might look like more code, but the responsibility is in the right place now

    0 讨论(0)
提交回复
热议问题