在NSThread问题上使用两个参数调用选择器
问题描述:
我想使用多个参数创建一个线程。 这可能吗? 我具备的功能:在NSThread问题上使用两个参数调用选择器
-(void) loginWithUser:(NSString *) user password:(NSString *) password { }
而且我要调用此功能选择:
[NSThread detachNewThreadSelector:@selector(loginWithUser:user:password:) toTarget:self withObject:@"someusername" withObject:@"somepassword"]; // this is wrong
如何通过这个detachNewThreadSelect功能上withObject参数两种说法?
可能吗?
答
你需要传递在传递的对象额外的参数,以withObject像这样:
NSDictionary *extraParams = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"user",@"password",nil] andKeys:[NSArray arrayWithObjects:@"valueForUser",@"valueForPassword",nil]]
[NSThread detachNewThreadSelector:@selector(loginWithUser:) toTarget:self withObject:extraParams];
答
包装你选择的方法有辅助包装方法,“wrappingMethod
”,即处理输入一个NSArray以满足您自己的方法在wrappingMethod
之前调用你自己的方法。现在分离一个NSThread,选择所有新的wrappingMethod
并将的NSArray实例。
另外:如果您的原始方法将一个或多个基本类型作为输入,然后您必须使用NSNumber或NSStrings来满足NSThread,那么在这里使用包装会特别有用。
答
这是从我的头顶,未经测试:
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"];
答
更新到ennuikiller的不错的答案:
NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:@"IMG_URL_VALUE",@"img_url",@"PARAM2_VALUE", @"param2", nil];
[NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:params];
感谢伟大的回答这个问题@Lance。 – iPadDeveloper2011 2013-05-23 07:15:24
您在第一行的末尾忘了分号;-) – Ken 2018-02-04 13:08:37