2010-02-24 29 views
15

我想使用多個參數創建一個線程。 這可能嗎? 我具備的功能:在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參數兩種說法?

可能嗎?

回答

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]; 
+0

感謝偉大的回答這個問題@Lance。 – iPadDeveloper2011 2013-05-23 07:15:24

+0

您在第一行的末尾忘了分號;-) – Ken 2018-02-04 13:08:37

0

包裝你選擇的方法有輔助包裝方法,「wrappingMethod」,即處理輸入一個NSArray以滿足您自己的方法在wrappingMethod之前調用你自己的方法。現在分離一個NSThread,選擇所有新的wrappingMethod並將的NSArray實例。

另外:如果您的原始方法將一個或多個基本類型作爲輸入,然後您必須使用NSNumber或NSStrings來滿足NSThread,那麼在這裏使用包裝會特別有用。

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"]; 
0

更新到ennuikiller的不錯的答案:

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

[NSThread detachNewThreadSelector:@selector(loadImage:) toTarget:self withObject:params]; 
相關問題