在 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];