目前我正在使用NSThread另一个线程缓存图像.
[NSThread detachNewThreadSelector:@selector(cacheImage:) toTarget:self withObject:image];
Run Code Online (Sandbox Code Playgroud)
交替:
[self performSelectorInBackground:@selector(cacheImage:) withObject:image];
Run Code Online (Sandbox Code Playgroud)
或者,我可以使用 NSOperationQueue
NSInvocationOperation *invOperation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(cacheImage:) object:image];
NSOperationQueue *opQueue = [[NSOperationQueue alloc] init];
[opQueue addOperation:invOperation];
Run Code Online (Sandbox Code Playgroud)
有没有理由改变NSThread?GCD是iPhone上发布的第四个选项,但除非有显着的性能提升,否则我宁愿坚持使用适用于大多数平台的方法.
根据@ Jon-Eric的建议,我选择了NSOperationQueue/ NSOperation子类解决方案.它工作得很好.该NSOperation班是足够灵活,你可以调用,块或定制子类使用它,这取决于你的需求.无论您如何创建自己,NSOperation都可以在准备运行时将其放入操作队列中.如果需要,这些操作可以作为您放入队列的对象,也可以作为独立的异步方法运行.由于您可以轻松地同步运行自定义操作方法,因此测试非常简单.
我在一些项目中使用了相同的技术,因为我问了这个问题,我对它保持我的代码和我的测试干净,有条理和快乐异步的方式感到高兴.
A +++++++++++++++++++++++++
在什么情况下你更喜欢使用NSOperationQueueGCD?
根据我对这两者的有限经验,我认为NSOperationQueue你基本上可以控制有多少并发操作.
使用GCD,您无法执行此操作,因为您正在使用队列.除了你可以用多核处理器以某种方式模拟这个,虽然我仍然认为没有办法控制它.
multithreading cocoa-touch nsoperationqueue grand-central-dispatch ios