2011-06-03 100 views
2

下面给出的示例代码:如何重复ASIHTTPRequest?

// 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. 
} 

当我从UIViewController类似[exampleModel sendRequest],它的工作原理!但是,后来我从另一个UIViewController再做[exampleModel sendRequest]并获得:

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

我该如何解决这个问题?

回答

6

你不应该尝试重用请求对象。它保持状态。真正的设计是在请求结束后处理掉。这个设计并不像NSURLConnection,NSURLRequest,NSURLResponse类(基本上将所有三合一化为一体,并包装底层的低级核心基础类)那样干净。如果你需要处理低层次的HTTP内容,它仍然比使用NSURLConnection更好。如果你不这样做,高级类有一些优点(比如访问UIWebView使用的相同缓存)。

+1

因此,我不会建议您的请求作为实例变量,因为它被设计为一次性的。如果您希望模型对象发出请求,但是从控制器触发它(这正是我想要做的),最好从控制器向模型发送通知,并让侦听器调用sendRequest。您仍然可以从控制器传入内容,但您不太可能遇到问题。 – 2011-06-03 01:58:38

+0

@Alec Sloman,所以,如果我将请求作为本地变量并在'requestFinished'&'requestFailed'回调中释放它,那么在调用这些回调之前如果模型是dealloc'ed会发生什么?那么,请求将永远不会被释放,对吗?这不是潜在的内存泄漏吗? – ma11hew28 2011-06-03 02:26:16

+0

@MattDiPasquale是的,这是完全正确的。但我不确定为什么你会让你的模型在你的请求完成之前被释放。您可以查询请求以查看它是否已完成。如果希望按照您所描述的方式发布您的模型,您可以考虑处理该问题。 – 2011-06-03 04:02:02

1

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

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