I am studing about NSOperation and I have a doubt about the correct way of implementing it for my situation.
In my app I want to perfom a lot of operations in background. Since my app can import data from a desktop software, my database can become very large depending of the situation. With this, reading and analysing data can take a few seconds and I don't want my UI frozen during this time.
Lets supose that I have an class:
ClassX
- (void) heavyOp1
- (void) heavyOp2
- (void) heavyOp3
Each heavyOp is related with ClassX
, so it makes sense that they belong to the same class.
My questions and my options:
1) Should ClassX
be a subclass of NSOperation
?
I understood that operations should represent one task, but my class offers 3 different tasks. I could try to control the execution with some custom constructors, but I think that I am probably breaking a concept.
2) Using NSInvocationOperation
is correct? I can't cancel it!
I know that I can do something like that:
ClassX *myClassX = [[ClassX alloc] init];
NSInvocationOperation *myOp = [[NSInvocationOperation alloc] initWithTarget:myClassX selector:@selector(heavyOp1) object:nil];
NSOperationQueue *myQueue = [[NSOperationQueue alloc] init];
[myQueue myOp];
but if I call [myQueue cancelAllOperations];
the ClassX
will not respond to self.isCancelled
because it don't exist in NSInvocationOperation
.
Forcing the class recognize with some code like this [myOp addObserver:myClassX forKeyPath:@"isCancelled" options:NSKeyValueObservingOptionNew context:nil];
works, but again I think that I am breaking concepts.
3) Create a subclass of NSOperation
for each heavyOp method from my ClassX
?
That would generate a lot of subclasses and can be hard to manage it, I don't know if its correct.
So, what is the correct way to solve the problem? Anyone can give me advices? Maybe I am wrong with one of the options that I explained. If something is not clear, just ask and I will try to explain better.
I tend to think of NSInvocationOperation
being used to retro-fit operations and queues to existing code. If I was starting from scratch, or even if I wanted more fine-grained control (the ability to cancel as you mention) I would definitely create subclass(es) of NSOperation
.
Without knowing exactly what your heavy operations are it's hard to say with certainty, but I would also be inclined to create them as three separate classes. Cancelling each op may have different things that need to be done, so it's clear to have the code to perform that cancellation in separate classes.