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]からのようなことをすると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クラスほどクリーンではありません(基本的に、3つすべてを1つにマッシュアップし、その下にある低レベルのコア基盤クラスをラップします)。低レベルの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 に答える