views:

445

answers:

2

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?

+4  A: 

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

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

[NSThread detachNewThreadSelector:@selector(loginWithUser:) toTarget:self withObject:extraParams]; 
ennuikiller
A: 

Wrap your selected method with an auxiliary wrapping method, "wrappingMethod", that processes an NSArray of inputs to suit your own method before calling your own method within wrappingMethod. Now detach an NSThread that selects your all new wrappingMethod and takes the NSArray instance for withObject.

Aside: Having a wrapper here can be particularly helpful if your original method takes one or more primitive types as input and you then have to work with NSNumber or NSStrings, say, to satisfy NSThread.

SpecialK