ASIHTTPRequest令人烦恼

时间:2011-12-09 21:06:46

标签: iphone ios xcode request asihttprequest

我正在尝试使用wordpress api,但我的请求有未知问题: 第一个请求工作完美,但第二个请求崩溃。我的代码:

//Response from request, which was before
        NSString *responseString = [request responseString];
        SBJsonParser *jsonParser = [SBJsonParser new];
        NSDictionary *dict = (NSDictionary*)[jsonParser objectWithString:responseString];
        [jsonParser release];
        int count = 10
        int loadingNow = 1;
        while (loadingNow <= count) {
            NSDictionary *currentPostDict = (NSDictionary *)[fullPosts objectAtIndex:(loadingNow - 1)];
            NSString *currentSlug = (NSString *)[currentPostDict objectForKey:@"slug"];
            if (loadingNow == 1) {
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.smartfiction.ru/api/get_post/?slug=%@", currentSlug]];
                NSLog(@"url: %@", url);
                ASIHTTPRequest *requestNew = [ASIHTTPRequest requestWithURL:url];
                [requestNew setDelegate:self];
                [requestNew setDidFinishSelector:@selector(requestDidFinishForThreadID:)];
                [requestNew setTag:1];
                [requestNew startAsynchronous];
                [url release];
            }
        }

我的网址如下: http://www.smartfiction.ru/api/get_post/?slug=best_friend

错误地点:      //在ASIHTTPRequest.m中         NSArray * cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[[self url] absoluteURL]];

3 个答案:

答案 0 :(得分:2)

设置NSURL * url的行返回一个自动释放的对象,因此您不希望稍后在该系列语句中释放它。

答案 1 :(得分:2)

解决方案:

你应该摆脱这条线......

[url release];

发生了什么?

这是设置问题的地方......

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.smartfiction.ru/api/get_post/?slug=%@", currentSlug]];

你在这里做了什么并没有错。但是这个方法返回一个自动释放的NSURL。这意味着一旦你的url变量超出范围,autoReleasePool就可以在下次应用程序运行它的下一个周期时释放它。

当您使用[url release]手动释放它时,它会获得零保留计数并很快被取消分配。然后,当您下次尝试访问它时,它就不再存在了,操作系统会让您失望。

那么,这里发生了什么?

如果通过向类发送alloc消息来创建对象,则“拥有”该对象并负责在适当的时间释放它。除此之外,当您使用其中一个类构造函数时,该对象已经自动释放,您不负责释放它。

一般情况下,您应该将每个allocreleaseautorelease配对。

答案 2 :(得分:1)

由于您没有通过alloc,new或副本获取NSURL实例,并且未明确保留它,因此您没有所有权&#39;在对象上。在没有所有权的情况下释放它是内存管理错误。 有关详细信息,请参阅http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmRules.html#//apple_ref/doc/uid/20000994-BAJHFBGH