2011-12-02 121 views
1

我正在嘗試使用ASIHTTPRequest爲iOS創建應用程序,但我正面臨着使用它的一些問題。爲了演示我的問題,我已經上傳了一個測試項目,您可以從這裏下載:http://uploads.demaweb.dk/ASIHTTPRequestTester.zipASIHTTPRequestTester:異步不起作用

我已經創建了使用ASIHTTPRequestDelegate協議的WebService類:

#import "WebService.h" 
#import "ASIHTTPRequest.h" 

@implementation WebService 

- (void)requestFinished:(ASIHTTPRequest *)request { 
    NSLog(@"requestFinished"); 
} 
- (void)requestFailed:(ASIHTTPRequest *)request { 
    NSLog(@"requestFailed"); 
} 

- (void) testSynchronous { 
    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    NSLog(@"starting Synchronous"); 
    [request startSynchronous]; 
    NSError *error = [request error]; 
    if (!error) { 
     NSLog(@"got response"); 
    } 
} 

- (void) testAsynchronous { 
    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    [request setDelegate:self]; 

    NSLog(@"starting Asynchronous"); 
    [request startAsynchronous]; 
} 

@end 

同步方法工作正常,但是在異步不工作的。首先requestFinished和requestFailed從未被調用,現在我得到一個EXC_BAD_ACCESS。這兩個測試方法是從我的ViewController的viewDidLoad調用的。我希望有人能幫助我完成這項工作。

EDIT1:this topic,這是可能的,因爲這是我的項目使Automatic Reference Counting的。該主題的建議添加一個[self retain],但我不能用ARC打開。任何人都有解決方案嗎?

編輯2: 根據MrMage的回答更新。

@interface ViewController() 
@property (nonatomic,strong) WebService *ws; 
@end 

@implementation ViewController 

@synthesize ws = _ws; 

#pragma mark - View lifecycle 
- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    [self setWs:[[WebService alloc] init]]; 
    [self.ws testSynchronous]; 
    [self.ws testAsynchronous]; 
} 

@end 

回答

3

您可以添加您的WebService實例作爲強引用一個對象,它總是在那裏,足夠長的時間(比如您的視圖控制器),然後告訴該類擺脫WebService它已經完成了它的任務後(即在requestFinishedrequestFailed中,您可以回叫視圖控制器,告訴它釋放WebService實例)。

+0

感謝您的回答。請參閱我的'edit2',我已經在ViewController中添加了一個強大的屬性。它工作正常,但有沒有更好的方法來做到這一點? – dhrm

0

我在ASIHTTPRequest和ARC的授權上遇到了同樣的問題。

我只是最終使用塊來解決它。

NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 

//set request like this to avoid retain cycle on blocks 
__weak ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 

//if request succeeded 
[request setCompletionBlock:^{   
    [self requestFinished:request]; 
}]; 

//if request failed 
[request setFailedBlock:^{   
    [self requestFailed:request]; 
}]; 

[request startAsynchronous];