In my app I'm trying to implement a NSOperationQueue
for the web service interaction using AFNetworking
. I'm adding a NSOperation
one by one into the queue. I want to cancel a particular operation at any time. For that I want to set some unique key to the operation. So, is there any way possible to achieve it?
Asked
Active
Viewed 700 times
3

ricardopereira
- 11,118
- 5
- 63
- 81

iOS
- 139
- 5
1 Answers
3
Create a NSOperation
sub class and set one property.
If the app minimum deployment is greater than iOS 8, then you can directly use the .name
property.
NSOperationQueue *queue = [NSOperationQueue mainQueue];
if (![[[queue operations] valueForKey:@"name"] containsObject:@"WS"])
{
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
//your task
}];
op.name = @"Unique id";
[queue addOperation:op];
}
else
{
NSIndexSet *indexSet = [[queue operations] indexesOfObjectsPassingTest:
^ BOOL(NSBlockOperation *obj, NSUInteger idx, BOOL *stop)
{
if ([obj.name isEqualToString:@"Unique id"])
{
return YES;
} else
{
return NO;
}
*stop = YES;
} ];
if (indexSet.firstIndex != NSNotFound)
{
NSBlockOperation *queryOpration = [[queue operations] objectAtIndex:indexSet.firstIndex];
[queryOpration cancel];
}
}
If the app is not for iOS 8 or greater, then you can create a subclass of the NSOperation
and set an identity with the possibility to query with that value:
@interface WSOperation: NSOperation
@property (nonatomic, strong) NSString* operationID;
@end

ricardopereira
- 11,118
- 5
- 63
- 81

Parth Patel p1nt0z
- 583
- 4
- 17
-
I don't recommend using `operations` nor `operationCount`, because both are inherently a race condition and those should be avoided. Both are deprecated since iOS 13. – ricardopereira Oct 08 '19 at 13:20