项目从AFN 2.0 迁移到 3.0,因为代码历史问题,需要通过NSURLSessionTask 获取到responseString,可是通过category 无法添加属性以及方法
由于category 中需要用到reposne 中的数据,所以也无法直接给 NSObject 添加category,各位大大,是否有好的解决方案
PHP中文网2017-04-18 09:08:28
NSURLSessionTask indeed cannot add category, which is somewhat similar to the problem of "cannot be inherited". Generally, there are several ideas when encountering this kind of problem. See if it can be used for your business:
Combination instead of inheritance, define a NSURLSessionTaskWrapper, which has an attribute that is the task, and you can add any other attributes and methods you want; you can use the part that uses the task directly wrapper.task
, or you can write a method for transparent transmission, such as
- (NSInteger)someProperty {
return self.task.someProperty;
}
Of course, you can control the use of your own code wrapper.task
, but you cannot control the code of the system, so I don’t know whether it can be used for your business.
Use runtime to add attributes and methods. This can solve the above problem of "not being able to control the system's code". After using the runtime to modify it, this class will have these attributes and methods in the eyes of the system. But I can’t add category. I don’t know if runtime works.
External storage. Find out if the sessionTask has an attribute suitable for use as a unique id, and then write a SessionTaskManager class. The newly added methods are placed in this manager class. For the newly added attributes, the manager can save a dictionary with the id of the sessionTask as the key. Specifically The attribute is a value, and when needed, it is accessed based on the id.
The above are several commonly used ideas. You can see if they are applicable to your business~
ringa_lee2017-04-18 09:08:28
Updated on June 3, 2016 21:29:15
Added the extension to the
for the reasons mentioned by http://stackoverflow.com/a/35359533NSObject
classFor some reasons, please do not add just one category to the file. The detailed reasons can be viewed at https://developer.apple.com/library/mac/qa/qa1490/_index.html.
@interface NSObject (sun)
- (void)_sun_setResponseString:(NSString *)responseString;
- (NSString *)_sun_responseString;
@end
@implementation NSObject (sun)
static int _sun_ResponseStringKey;
- (void)_sun_setResponseString:(NSString *)responseString {
objc_setAssociatedObject(self, &_sunResponseStringKey, responseString, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)_sun_responseString {
return objc_getAssociatedObject(self, &_sunResponseStringKey);
}
@end
[_sessionManager setDataTaskDidReceiveDataBlock:^(NSURLSession *_Nonnull session, NSURLSessionDataTask *_Nonnull dataTask, NSData *_Nonnull data) {
[dataTask _sun_setResponseString:[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]];
NSLog(@"%@", [dataTask _sun_responseString]);
}];
The questioner can see if the above code can achieve the requirement.