从Parent Class的实例实例化Subclass

时间:2013-10-11 17:48:55

标签: objective-c

不需要以前的AFNetworking知识,但它可能会有所帮助。

我正在使用AFNetworking,我想创建一个AFHTTPRequestOperation的子类,它有一些额外的属性和方法。

我遇到的问题是我正在使用AFHTTPRequestOperationManager的工厂方法来生成我的AFHTTPRequestOperations,我显然不想更改AFNetworking库中的任何核心代码。

所以我想做的是这样的事情:

@implementation VP_AFHTTPRequestOperation : AFHTTPRequestOperation

+ (id)instantiateUsingAFHTTPRequestOperation:(AFHTTPRequestOperation*)reqOp {
    //I want to create an instance of VP_AFHTTPRequestOperation using the reqOp
    self = reqOp; //I can't just do this, but I don't know what to do
    return self;
}

- (void)mySubclassMethod { /* ... */ }
@end

我很感激任何建议

2 个答案:

答案 0 :(得分:0)

子类AFHTTPRequestOperationManager并使其返回HTTPRequestOperationWithRequest

中的好东西

不需要修改任何框架代码AFAICS

@interface VP_AFHTTPRequestOperationManager : AFHTTPRequestOperationManager 
@end     

@implementation VP_AFHTTPRequestOperationManager

+ (instancetype)manager { 
    return [[[self class] alloc] init]; 
}

- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)request
                                                success:(void (^) (AFHTTPRequestOperation *operation, id responseObject))success
                                                failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
    VP_AFHTTPRequestOperation *operation = [[VP_AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = self.responseSerializer;
    operation.shouldUseCredentialStorage = self.shouldUseCredentialStorage;
    operation.credential = self.credential;
    operation.securityPolicy = self.securityPolicy;

    [operation setCompletionBlockWithSuccess:success failure:failure];

    return operation;
}

@end

答案 1 :(得分:0)

我认为你可以通过继承AFHTTPRequestOperationManager并在覆盖AFHTTPRequestOperation的情况下使用HTTPRequestOperationWithRequest:success:failure的子类来做你想做的事。它在文档中简明扼要地描述:

  

更改所有请求操作构造的行为   AFHTTPRequestOperationManager子类,覆盖   HTTPRequestOperationWithRequest:成功:失败