如何在iOS中将唯一键值设置为NSOperation

问题描述 投票:1回答:1

[在我的应用中,我正在尝试使用NSOperationQueue为Web服务交互实现AFNetworking。我正在队列中一个NSOperation一一添加。我想随时取消特定操作。为此,我想为该操作设置一些唯一的键。那么,有什么方法可以实现?

ios objective-c afnetworking-2 nsoperation nsoperationqueue
1个回答
3
投票

创建一个NSOperation子类并设置一个属性。

如果应用程序的最低部署大于iOS 8,则可以直接使用NSOperation属性。

.name

如果该应用程序不适用于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];
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.