2

有没有办法如何拥有userInfo NSDictionarya NSOperation

基本上我想为一个 NSOperation 分配一个 ID,稍后我想检查这个 ID 是否已经分配给一个 NSOperation

- (void)processSmthForID:(NSString *)someID {

    for (NSOperation * operation in self.precessQueue.operations) {

        if ([operation.userInfo[@"id"] isEqualToString:someID]) {
            // already doing this for this ID, no need to create another operation
            return;
        }

    }

    NSOperation * newOperation = ...
    newOperation.userInfo[@"id"] = someID;

    // enqueue and execute

}
4

2 回答 2

6

NSOperation意味着被子类化。只需设计自己的子类。

NSOperation 类是一个抽象类,用于封装与单个任务关联的代码和数据。因为它是抽象的,所以不要直接使用这个类,而是子类化或使用系统定义的子类之一(NSInvocationOperation 或 NSBlockOperation)来执行实际任务。

在这里阅读

我同意@Daij-Djan 关于userInfo属性添加的观点。
此属性可以作为扩展来实现NSOperation(请参阅他的实现答案)。
但是,对 an 标识符的需求NSOperation是类的特殊化(您可以说新类是 an IdentifiableOperation

于 2013-04-27T11:13:06.250 回答
1

在 NSOperation 上定义一个属性,如下所示:

#import <Foundation/Foundation.h>
#import <objc/runtime.h>

//category
@interface NSOperation (UserInfo)
@property(copy) NSDictionary *userInfo;
@end

static void * const kDDAssociatedStorageUserInfo = (void*)&kDDAssociatedStorageUserInfo;

@implementation NSOperation (UserInfo)

- (void)setUserInfo:(NSDictionary *)userInfo {
    objc_setAssociatedObject(self, kDDAssociatedStorageUserInfo, [userInfo copy], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSDictionary *)userInfo {
    return objc_getAssociatedObject(self, kDDAssociatedStorageUserInfo);
}

@end

thaat 为您提供任何 NSOperation 或其子类的用户信息...例如 NSBlockOperation 或 AFHTTPRequestOperation

演示:

    //AFNetwork test
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.google.de"]]];
    operation.userInfo = @{@"url":operation.request.URL};
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"download of %@ completed. userinfo is %@", operation.request.URL, operation.userInfo);
        if(queue.operationCount==0)
            exit(1);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"download of %@ failed. userinfo is %@", operation.request.URL, operation.userInfo);
        if(queue.operationCount==0)
            exit(1);
    }];
    [queue addOperation:operation];
于 2013-04-27T11:49:42.033 回答