【发布时间】:2023-03-13 01:15:01
【问题描述】:
在我的应用程序中,我尝试使用 AFNetworking 为 Web 服务交互实现 NSOperationQueue。我正在将NSOperation 一个一个添加到队列中。我想随时取消特定操作。为此,我想为操作设置一些唯一键。那么,有没有什么办法可以实现呢?
【问题讨论】:
标签: ios objective-c afnetworking-2 nsoperation nsoperationqueue
在我的应用程序中,我尝试使用 AFNetworking 为 Web 服务交互实现 NSOperationQueue。我正在将NSOperation 一个一个添加到队列中。我想随时取消特定操作。为此,我想为操作设置一些唯一键。那么,有没有什么办法可以实现呢?
【问题讨论】:
标签: ios objective-c afnetworking-2 nsoperation nsoperationqueue
创建一个NSOperation 子类并设置一个属性。
如果应用最小部署大于iOS 8,则可以直接使用.name属性。
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];
}
}
如果应用程序不适用于 iOS 8 或更高版本,那么您可以创建 NSOperation 的子类并设置一个身份,以便使用该值进行查询:
@interface WSOperation: NSOperation
@property (nonatomic, strong) NSString* operationID;
@end
【讨论】:
operations 或operationCount,因为两者本质上都是竞争条件,应该避免。自 iOS 13 起,两者均已弃用。