跨视图控制器共享NSOperationQueue? [英] Sharing NSOperationQueue across View Controllers?

查看:90
本文介绍了跨视图控制器共享NSOperationQueue?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用NSOperationQueue来管理HTTP连接(使用ASI-HTTPRequest)。由于我有多个视图,并且需要让这些不同的视图请求HTTP连接,我应该尝试在app委托中创建全局NSOperationQueue,还是应该在每个视图中都有一个?我不熟悉NSOperationQueue。

I'm using an NSOperationQueue to manage HTTP connections (using ASI-HTTPRequest). Since I have multiple views and the need to have these different views requesting HTTP connections, should I try to create a global NSOperationQueue in the app delegate, or should I have one in each of the views? I'm not familiar with NSOperationQueue.

我想知道a)最佳做法是什么,b)如果没有最佳实践,权衡是什么如果有的话。

I'd like to know a) what the best practice is and b) if there is no best practice, what the tradeoffs are if any.

我确实尝试将操作队列放在类中(作为属性)处理服务器连接,但任务从未触发过。无法弄清楚,但[队列操作] = 0.如果有人知道解决方案,我认为这将是最好的放置它。

I did try to put the operation queue in the class (as a property) where I handle the server connections but the task never fired. Couldnt figure it out but [queue operations] = 0. If someone knows a solution to this, I presume this would be the best place to put it.

推荐答案

我已经通过在NSOperationQueue上添加一个我认为Apple错过的类方法来解决这个问题。共享操作队列。我将此作为NSOperationQueue上的类别添加为:

I have solved this by adding a class method on NSOperationQueue that I think Apple has missed; a shared operation queue. I add this as a category on NSOperationQueue as this:

// NSOperationQueue+SharedQueue.h
@interface NSOperationQueue (SharedQueue)
+(NSOperationQueue*)sharedOperationQueue;
@end

// NSOperationQueue+SharedQueue.m
@implementation NSOperationQueue (SharedQueue)
+(NSOperationQueue*)sharedOperationQueue;
{
  static NSOperationQueue* sharedQueue = nil;
  if (sharedQueue == nil) {
    sharedQueue = [[NSOperationQueue alloc] init];
  }
  return sharedQueue;
}
@end

这样我就不需要管理整个一群队列,除非我真的需要。我可以从所有视图控制器轻松访问共享队列。

This way I do not need to manage a whole bunch of queues unless I really need to. I have easy access to a shared queue from all my view controllers.

我甚至为NSObject添加了一个类别,以便更容易在此共享队列上添加新操作:

I have even added a category to NSObject to make it even easier to add new operations on this shared queue:

// NSObject+SharedQueue.h
@interface NSObject (SharedQueue)
-(void)performSelectorOnBackgroundQueue:(SEL)aSelector withObject:(id)anObject;
@end

// NSObject+SharedQueue.m
@implementation NSObject (SharedQueue)
-(void)performSelectorOnBackgroundQueue:(SEL)aSelector withObject:(id)anObject;
{
  NSOperation* operation = [[NSInvocationOperation alloc] initWithTarget:self
                                                                selector:aSelector
                                                                  object:anObject];
  [[NSOperationQueue sharedOperationQueue] addOperation:operation];
  [operation release];
}
@end

这篇关于跨视图控制器共享NSOperationQueue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆