在NSThread问题上调用带有两个参数的选择器

时间:2010-02-24 16:26:22

标签: iphone objective-c nsthread

我想用多个参数创建一个Thread。 可能吗? 我有这个功能:

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

我想把这个函数称为选择器:


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


如何在这个detachNewThreadSelect函数上传递关于withObject参数的两个参数?

有可能吗?

4 个答案:

答案 0 :(得分:16)

你需要在传递给withObject的对象中传递额外的参数,如下所示:

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

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

答案 1 :(得分: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"];

答案 2 :(得分:0)

使用辅助包装方法“wrappingMethod”包装所选方法,该方法在wrappingMethod内调用您自己的方法之前处理NSArray输入以适合您自己的方法。现在分离一个NSThread,它选择你的全新wrappingMethod并获取withObject的NSArray实例。

除此之外:如果您的原始方法将一个或多个基本类型作为输入,那么在此处使用包装器会特别有用,然后您必须使用NSNumber或NSStrings,例如,以满足NSThread。

答案 3 :(得分:0)

ennuikiller的更新答案:

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

[NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:params];