Subclases NSOperation para ser concurrente y cancelable
No puedo encontrar buena documentación sobre cómo subclasificarNSOperation
ser concurrente y también para apoyar la cancelación. Leí los documentos de Apple, pero no puedo encontrar un ejemplo "oficial".
Aquí está mi código fuente:
@synthesize isExecuting = _isExecuting;
@synthesize isFinished = _isFinished;
@synthesize isCancelled = _isCancelled;
- (BOOL)isConcurrent
{
return YES;
}
- (void)start
{
/* WHY SHOULD I PUT THIS ?
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
return;
}
*/
[self willChangeValueForKey:@"isExecuting"];
_isExecuting = YES;
[self didChangeValueForKey:@"isExecuting"];
if (_isCancelled == YES)
{
NSLog(@"** OPERATION CANCELED **");
}
else
{
NSLog(@"Operation started.");
sleep(1);
[self finish];
}
}
- (void)finish
{
NSLog(@"operationfinished.");
[self willChangeValueForKey:@"isExecuting"];
[self willChangeValueForKey:@"isFinished"];
_isExecuting = NO;
_isFinished = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
if (_isCancelled == YES)
{
NSLog(@"** OPERATION CANCELED **");
}
}
En el ejemplo que encontré, no entiendo por qué se utiliza performSelectorOnMainThread: Evitaría que mi operación se ejecute simultáneamente.
Además, cuando comento esa línea, hago que mis operaciones se ejecuten simultáneamente. sin embargo, elisCancelled
La bandera no se modifica, aunque he llamadocancelAllOperations
.