有没有一种方法可以让NSOperation的userInfo NSDictionary
基本上,我想给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
}发布于 2013-04-27 19:13:06
NSOperation应该是子类化的。只需设计自己的子类即可。
NSOperation类是一个抽象类,用于封装与单个任务关联的代码和数据。因为它是抽象的,所以不直接使用这个类,而是子类化或使用系统定义的子类(NSInvocationOperation或NSBlockOperation)来执行实际任务。
read here
我同意@Daij-Djan关于添加userInfo属性的观点。
这个属性可以作为NSOperation上的一个扩展来实现(请参考他对实现的回答)。
然而,对于NSOperation的标识符的需要是类的专门化(您可以说新类是IdentifiableOperation)
发布于 2013-04-27 19:49:42
在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这会让你在任何NSOperation或它的子类上得到一个userInfo ...例如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];https://stackoverflow.com/questions/16251257
复制相似问题