次のように 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 またはそのサブクラスで 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];