如何重复ASIHTTPRequest?

时间:2011-06-03 01:06:40

标签: iphone objective-c asihttprequest nsoperationqueue

给出以下示例代码:

// ExampleModel.h

@interface ExampleModel : NSObject <ASIHTTPRequestDelegate> {

}

@property (nonatomic, retain) ASIFormDataRequest *request;
@property (nonatomic, copy) NSString *iVar;

- (void)sendRequest;


// ExampleModel.m

@implementation ExampleModel

@synthesize request;
@synthesize iVar;

# pragma mark NSObject

- (void)dealloc {
    [request clearDelegatesAndCancel];
    [request release];
    [iVar release];
    [super dealloc];
}

- (id)init {
    if ((self = [super init])) {
        // These parts of the request are always the same.
        NSURL *url = [[NSURL alloc] initWithString:@"https://example.com/"];
        request = [[ASIFormDataRequest alloc] initWithURL:url];
        [url release];
        request.delegate = self;
        [request setPostValue:@"value1" forKey:@"key1"];
        [request setPostValue:@"value2" forKey:@"key2"];
    }
    return self;
}

# pragma mark ExampleModel

- (void)sendRequest {
    // Reset iVar for each repeat request because it might've changed.
    [request setPostValue:iVar forKey:@"iVarKey"];
    [request startAsynchronous];
}

@end

# pragma mark ASIHTTPRequestDelegate

- (void)requestFinished:(ASIHTTPRequest *)request {
    // Handle response.
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    // Handle error.
}

当我从[exampleModel sendRequest]执行类似UIViewController的操作时,它可以正常工作!但是,我再次从另一个[exampleModel sendRequest] UIViewController获得并获得:

Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '*** -[NSOperationQueue addOperation:]:
operation is finished and cannot be enqueued`

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:6)

您不应尝试重用请求对象。它保持状态。真的设计为在请求结束后处理掉。

设计不像NSURLConnection,NSURLRequest,NSURLResponse类那样干净(基本上将三者合并为一个并将下面的低级核心基础类包装起来)。如果您需要处理低级别的HTTP内容,它仍然比以一种普通方式使用NSURLConnection要好得多。如果不这样做,高级类有一些优点(比如访问UIWebView使用的相同缓存)。

答案 1 :(得分:2)

答案 2 :(得分:1)

ASIHTTPRequest及其子类符合NSCopying协议。就这样做:

 ASIFormDataRequest *newRequest = [[request copy] autorelease];
 [newRequest startAsynchronous];