2

给出下面的示例代码:

// 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]当我从 a做类似的事情时UIViewController,它可以工作!但是,然后我[exampleModel sendRequest]又从另一个人UIViewController那里得到:

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

我怎样才能解决这个问题?

4

3 回答 3

6

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

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

于 2011-06-03T01:19:13.387 回答
2

我想我找到了答案:https ://groups.google.com/d/msg/asihttprequest/E-QrhJApsrk/Yc4aYCM3tssJ

于 2011-06-03T01:10:11.773 回答
1

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

 ASIFormDataRequest *newRequest = [[request copy] autorelease];
 [newRequest startAsynchronous];
于 2011-06-03T02:38:24.537 回答