ASIHTTPRequestTester:异步无法正常工作

时间:2011-12-02 11:55:56

标签: objective-c ios cocoa-touch asihttprequest

我正在尝试使用ASIHTTPRequest为iOS制作应用程序,但我在使用它时遇到了一些问题。为了证明我的问题,我上传了一个测试项目,你可以从这里下载:http://uploads.demaweb.dk/ASIHTTPRequestTester.zip

我创建了一个使用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: 根据{{​​3}},可能因为我的项目启用了Automatic Reference Counting。添加[self retain]的主题建议,但是我无法在启用ARC的情况下执行此操作。有解决方案的人吗?

EDIT2: 根据{{​​3}}的答案进行更新。

@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

2 个答案:

答案 0 :(得分:3)

你可以添加你的WebService实例作为对一个长时间保持足够长的对象(比如你的视图控制器)的强引用,然后告诉该类在它之后摆脱WebService完成了它的工作(即在requestFinishedrequestFailed中回调视图控制器,告诉它释放WebService实例。

答案 1 :(得分: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];
相关问题