16

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

4 回答 4

16

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]; 
于 2010-02-24T16:30:48.607 回答
6

这是我的头顶,未经测试:

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

然后你可以导入NSThread+ManyObjects并调用

[NSThread detachNewThreadSelector:@selector(loginWithUser:user:password:) toTarget:self withObject:@"someusername" andObject:@"somepassword"];
于 2011-12-14T09:07:13.123 回答
1

对 ennukiller 的好回答的更新:

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

[NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:params];
于 2014-11-28T13:59:08.753 回答
0

使用辅助包装方法“ wrappingMethod”包装您选择的方法,该方法会在wrappingMethod. 现在分离一个 NSThread ,它选择你的全新wrappingMethod并获取 NSArray 实例withObject

另外:如果您的原始方法将一个或多个原始类型作为输入,然后您必须使用 NSNumber 或 NSStrings 来满足 NSThread,那么这里有一个包装器会特别有用。

于 2010-10-25T11:19:59.707 回答