PerformSelector在特定的线程中

时间:2014-08-22 18:18:08

标签: objective-c multithreading nsthread performselector

我拥有一个同时发送文件到Web服务器(图像,文本,音频)的应用程序,而不是权衡主线程,我想我会在苹果线程中的现有设备之间分配这些操作。 / p>

我在调试中看到xcode模拟器有5个线程,我尝试这样做:

[self performSelector:@selector(SendImages) onThread:1 withObject:nil waitUntilDone:NO];
[self performSelector:@selector(SendText) onThread:2 withObject:nil waitUntilDone:NO];
[self performSelector:@selector(SendAudio) onThread:3 withObject:nil waitUntilDone:NO];

在这段代码中,我使用3个线程来执行不同的功能,但是我对这段代码有两个问题:

  

将“int”发送到参数的指针转换不兼容   类型'NSThread *'

     

线程1:EXC_BAD_ACCESS(代码= 2;地址= 0x3)

我该如何解决这个问题? (ARC在我的项目中禁用)

1 个答案:

答案 0 :(得分:0)

为了使用performSelector:onThread:withObject:waitUntilDone:,您需要对NSThread对象的引用,而不是整数(可能您认为这是一个线程数组的索引?)。

如果您想在后台线程上执行这些操作,最好使用NSInvocationOperationNSOperationQueue,操作系统将为您管理后台线程。

例如:

@property (nonatomic, retain) NSOperationQueue *queue;

...

queue = [NSOperationQueue new];  
[queue setMaxConcurrentOperationCount:3]; 
NSInvocationOperation *operationImages = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(SendImages) object:nil] autorelease];  
NSInvocationOperation *operationText = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(SendText) object:nil] autorelease];  
NSInvocationOperation *operationAudio = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(SendAudio) object:nil] autorelease];  
[queue addOperation:operationImages];  
[queue addOperation:operationText];  
[queue addOperation:operationAudio];  
相关问题