给定以下示例代码:
// 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`
我怎样才能解决这个问题?
最佳答案
您不应该尝试重用请求对象。它保持状态。真正设计为在请求结束后进行处理。
该设计不如NSURLConnection,NSURLRequest,NSURLResponse类那么干净(基本上将这三个类全部融合为一个,并在其下包装了低层的核心基础类)。如果您需要处理低级的HTTP内容,它仍然比以香草方式使用NSURLConnection更好。如果您不这样做,那么高级类具有一些优点(例如访问UIWebView使用的相同缓存)。