2011-12-02 81 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];