oka*_*ami 15 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函数上传递onObject参数的两个参数?
可能吗?
enn*_*ler 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];
Run Code Online (Sandbox Code Playgroud)
这是我的头脑,未经测试:
NSThread+ManyObjects.h
:
@interface NSThread (ManyObjects)
+ (void)detachNewThreadSelector:(SEL)aSelector
toTarget:(id)aTarget
withObject:(id)anArgument
andObject:(id)anotherArgument;
@end
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
然后你可以导入NSThread+ManyObjects
和调用
[NSThread detachNewThreadSelector:@selector(loginWithUser:user:password:) toTarget:self withObject:@"someusername" andObject:@"somepassword"];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8093 次 |
最近记录: |