我可以找到有关 NSThreads 的所有示例/教程,我处理它们的唯一方法是[NSThread detachNewThreadSelector:@selector(processDataMethod) toTarget:self withObject:nil];
将方法中的所有处理移动到另一个拥有自己的 autoreleasePool 等的线程。
这对于应该执行并“消失”的“一次性”操作很有用。
我必须突发进行许多小型 Web 服务调用,并且我想创建一个在应用程序运行期间一直存在的 NSThread 对象。主要是为了防止在爆发时产生许多新线程。
我看了看,initWithTarget
这[NSThread start]
似乎与我正在尝试做的事情有关。我只是不确定如何将它放在一起,线程是否进入我的对象,我是否将对象传递给我的线程等。
以伪代码/解释方式,我试图实现这一点:
MyController;
@interface
NSThread *threadProperty; //a property, holding a thread I would like to message
MyWebService *webServiceObject; //the Class that holds web service methods e.g. - (NSArray*) searchFor:(NSString*) searchStr;
on viewDidLoad:
instantiate webServiceObject;
instantiate threadProperty;
hand threadProperty the webServiceObject.
start the thread. //make it go forever with [[NSRunLoop currentRunLoop] run];
on user does something:
tell the thread to tell the webServiceObject to searchFor:@"Foo";
on thread has a response:
thread says webServiceObject says there are 19 @"Foo" up in the cloud.
我一直在摆弄如何使它工作,但意识到我对这个主题的理解不够好,无法想出一个“模式”来实现它。我想我正在尝试在一个单独的连续线程中的对象上实现一组方法调用,而不是每次我需要调用一个特定方法时都生成一个线程(可能在 500 毫秒内连续 8 次。然后不在2 分钟)。
我希望这是有道理的,并且在线程方面更有经验的人可以为我指明正确的方向。
这篇文章非常接近我尝试过的内容:如何使用 performSelect...