Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling selector with two arguments on NSThread issue

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

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

And I want to call this function as a selector:


[NSThread detachNewThreadSelector:@selector(loginWithUser:user:password:) toTarget:self withObject:@"someusername" withObject:@"somepassword"]; // this is wrong


How to pass two arguments on withObject parameter on this detachNewThreadSelect function?

Is it possible?

like image 215
okami Avatar asked Feb 24 '10 16:02

okami


3 Answers

You need to pass the extra parameters in an object passed to withObject like so:

NSDictionary *extraParams = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"user",@"password",nil] andKeys:[NSArray arrayWithObjects:@"valueForUser",@"valueForPassword",nil]]

[NSThread detachNewThreadSelector:@selector(loginWithUser:) toTarget:self withObject:extraParams]; 
like image 185
ennuikiller Avatar answered Oct 13 '22 22:10

ennuikiller


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"];
like image 44
Simon Avatar answered Oct 13 '22 22:10

Simon


An update to ennuikiller's nice answer:

NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:@"IMG_URL_VALUE",@"img_url",@"PARAM2_VALUE", @"param2", nil];

[NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:params];
like image 36
voghDev Avatar answered Oct 13 '22 21:10

voghDev