Search code examples
objective-cxcodeglobalnsoperationnsoperationqueue

NSOperation in global queue


I'm already trying to understand whats wrong with my code for 2 days now. I hope you have an idea?

I'm trying to create a NSOperationQueue as a "global" queue to allow me to add operations from any method within that viewController. Before I tried to define the queue in the .h file to make it global I created it inside the method I needed it originally and I was able to add Operations. This worked well. But then I wanted to check if there were any active operations inside the queue from outside the original method, which I obviously couldn't because I declared it inside the method. So I tried to declare it in the .h with the following code:

@property (strong, nonatomic) NSOperationQueue *queue;

and in the top of .m:

@synthesize queue;

this is the code where I add the operation to the queue.

NSInvocationOperation *doMorse = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(morse) object:nil];

[self.queue addOperation:doMorse];

The problem is that the queue stays empty when I try to add an operation. (Which worked properly before.) Did I declare the queue wrong? By the way, is there a better solution to make the queue accessible from any method than the one I tried? (within the same viewController (if it would work from any view it would be awesome :-) )).

Thank you very much!


Solution

  • You need to actually create your queue. You only declare an instance variable to store the queue in.

    In your constructor (init method), add: self.queue = [[NSOperationQueue alloc] init]

    If it worked before but not any longer, you probably started calling another constructor. A mistake I commonly make is to do setup in initWithFrame: in my custom views, but then start using the view from a nib, which means initWithCoder: will be called instead.