与RKRequest一起使用sendAsynchronously时应用程序崩溃

时间:2012-10-10 09:41:30

标签: objective-c ios restkit

我想使用Restkit异步下载文件。但是,当使用sendAsynchronously方法时应用程序崩溃。如果我使用sendSynchronously而不是sendAsynchronously,它不会崩溃。有人知道为什么吗?

这是我的代码

NSString *passURL = @"https://s3.amazonaws.com/mheydt-mhtnd/2012-03-13-1.png";
        RKRequest *request = [RKRequest requestWithURL:[NSURL URLWithString: passURL]];
        request.delegate = self;
        [request sendAsynchronously];


- (void)request:(RKRequest *)request didReceiveResponse:(RKResponse *)response {
    NSLog(@"didReceiveResponse");
}

- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response {
   NSLog(@"didLoadResponse");   
}

非常感谢!

1 个答案:

答案 0 :(得分:0)

以这种方式使用sendAsynchronously时,不会保留请求。您最好使用send方法在RKRequestQueue的实例中添加请求(这会阻止请求过早释放):

[request send];

,您可以自己强烈引用该请求。您的代码将成为:

@interface MyClass
{
    RKRequest *request;
}

我们假设这是一个强有力的参考。在实施中,您将拥有:

@implementation MyClass

- (void)sendTheRequest
{
    NSString *passURL = @"https://s3.amazonaws.com/mheydt-mhtnd/2012-03-13-1.png";
    request = [RKRequest requestWithURL:[NSURL URLWithString: passURL]];
    request.delegate = self;
    [request sendAsynchronously];
}

- (void)request:(RKRequest *)request didReceiveResponse:(RKResponse *)response {
    NSLog(@"didReceiveResponse");
    request = nil;
}

- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response {
    NSLog(@"didLoadResponse");
    request = nil;
}

- (void)request:(RKRequest *)request didFailLoadWithError:(NSError *)error {
    NSLog(@"didFailLoadWithError");
    request = nil;
}

@end