performSelectorInBackground with multiple params

后端 未结 4 1900
孤街浪徒
孤街浪徒 2020-12-14 09:56

How can I call a method with multiple params like below with performSelectorInBackground?

Sample method:

-(void) reloadPage:(NSInteger)pageIndex fir         


        
4条回答
  •  爱一瞬间的悲伤
    2020-12-14 10:47

    I've just found this question and wasn't happy with any of the answers. In my opinion neither make good use of the tools available, and passing around arbitrary information in arrays and dictionaries generally worries me.

    So, I went and wrote a small NSObject category that will invoke an arbitrary selector with a variable number of arguments:

    Category Header

    @interface NSObject (NxAdditions)
    
    -(void)performSelectorInBackground:(SEL)selector withObjects:(id)object, ... NS_REQUIRES_NIL_TERMINATION;
    
    @end
    

    Category Implementation

    @implementation NSObject (NxAdditions)
    
    -(void)performSelectorInBackground:(SEL)selector withObjects:(id)object, ...
    {
        NSMethodSignature *signature = [self methodSignatureForSelector:selector];
    
        // Setup the invocation
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
        invocation.target = self;
        invocation.selector = selector;
    
        // Associate the arguments
        va_list objects;
        va_start(objects, object);
        unsigned int objectCounter = 2;
        for (id obj = object; obj != nil; obj = va_arg(objects, id))
        {
            [invocation setArgument:&obj atIndex:objectCounter++];
        }
        va_end(objects);
    
        // Make sure to invoke on a background queue
        NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithInvocation:invocation];
        NSOperationQueue *backgroundQueue = [[NSOperationQueue alloc] init];
        [backgroundQueue addOperation:operation];
    }
    
    @end
    

    Usage

    -(void)backgroundMethodWithAString:(NSString *)someString array:(NSArray *)array andDictionary:(NSDictionary *)dict
    {
        NSLog(@"String: %@", someString);
        NSLog(@"Array: %@", array);
        NSLog(@"Dict: %@", dict);
    }
    
    -(void)someOtherMethod
    {
        NSString *str = @"Hello world";
        NSArray *arr = @[@(1337), @(42)];
        NSDictionary *dict = @{@"site" : @"Stack Overflow",
                               @"url" : [NSURL URLWithString:@"http://stackoverflow.com"]};
    
        [self performSelectorInBackground:@selector(backgroundMethodWithAString:array:andDictionary:)
                              withObjects:str, arr, dict, nil];
    }
    

提交回复
热议问题