calling selector with two arguments on NSThread issue

后端 未结 4 1980
情深已故
情深已故 2020-12-31 05:27

I\'d like to make a Thread with multiple arguments. Is it possible? I have the function:

-(void) loginWithUser:(NSString *) user password:(NSString *) password {
         


        
4条回答
  •  感动是毒
    2020-12-31 05:54

    This is off the top of my head, untested:

    NSThread+ManyObjects.h:

    @interface NSThread (ManyObjects)
    
    + (void)detachNewThreadSelector:(SEL)aSelector
                           toTarget:(id)aTarget 
                         withObject:(id)anArgument
                          andObject:(id)anotherArgument;
    
    @end
    

    NSThread+ManyObjects.m:

    @implementation NSThread (ManyObjects)
    
    + (void)detachNewThreadSelector:(SEL)aSelector
                           toTarget:(id)aTarget 
                         withObject:(id)anArgument
                          andObject:(id)anotherArgument
    {
        NSMethodSignature *signature = [aTarget methodSignatureForSelector:aSelector];
        if (!signature) return;
    
        NSInvocation* invocation = [NSInvocation invocationWithMethodSignature:signature];
        [invocation setTarget:aTarget];
        [invocation setSelector:aSelector];
        [invocation setArgument:&anArgument atIndex:2];
        [invocation setArgument:&anotherArgument atIndex:3];
        [invocation retainArguments];
    
        [self detachNewThreadSelector:@selector(invoke) toTarget:invocation withObject:nil];
    }
    
    @end
    

    And then you can import NSThread+ManyObjects and call

    [NSThread detachNewThreadSelector:@selector(loginWithUser:user:password:) toTarget:self withObject:@"someusername" andObject:@"somepassword"];
    

提交回复
热议问题