首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有Json数据的NSAutoreleasePool

带有Json数据的NSAutoreleasePool
EN

Code Review用户
提问于 2011-09-17 00:10:53
回答 2查看 334关注 0票数 1

只需要知道我是不是做错了这段代码。我的应用程序现在似乎运行得很快,使用这段代码。我只想,如果我真的不喜欢

代码语言:javascript
复制
   - (void)receive
{


    NSString *post2 = [NSString stringWithFormat:@"expediteur=%@&destinataire=%@",
                       [[expediteurLbl text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                       [[destinataireLbl text] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    NSData *dataToSend2 = [NSData dataWithBytes:[post2 UTF8String] length:[post2 length]  ];

    request2 = [[[NSMutableURLRequest alloc] init] autorelease];
    [request2 setURL:[NSURL URLWithString:@"http:/****************.php"]];
    [request2 setHTTPMethod:@"POST"];
    [request2 setHTTPBody:dataToSend2];
    [request2 setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];

    [NSThread detachNewThreadSelector:@selector(displayView) toTarget:self withObject:nil]; 

    }

    -(void)displayView

    {
        NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
        NSURLResponse *response2;
        NSError *error2;
        NSData *data2 = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response2 error:&error2];
        reponseServeur2= [[NSMutableString alloc] initWithData:data2 encoding: NSASCIIStringEncoding];



        responseString2 = [[NSString alloc] initWithData:data2 encoding:NSUTF8StringEncoding];

        [[reponseServeur2 stringByReplacingOccurrencesOfString:@"\n"  withString:@""] mutableCopy];


        self.messageArray = [responseString2 JSONValue];
        [messTableView reloadData];




        [pool release];


    }

代码语言:javascript
复制
- (void)viewDidLoad {
    [super viewDidLoad];

    [self performSelectorInBackground:@selector(receive) withObject:nil];
}
EN

回答 2

Code Review用户

发布于 2011-09-17 00:34:22

我认为request2是一个实例变量?最好用一个自动释放的值来设置它,然后在您的displayView方法中期望它在后面是有效的。

但是它可能有效,因为您在后台任务中执行receive,并且后台任务没有默认的自动释放池。如果不是那样的话,request2很可能会在到达displayView之前“喝”一杯。

因此,receive中的所有自动发布的数据项-- post2、dataToSend2、request2、几个临时字符串和至少一个临时URL --都在泄漏。

票数 2
EN

Code Review用户

发布于 2011-09-17 00:40:23

只需要知道我是不是做错了这段代码。

简短的回答是肯定的。

  1. request2是在与其引用的线程不同的线程中被分配和自动释放的,并且在您在displayView中使用它之前可能会被取消分配。这将是一种“种族状况”,你可能不会看到它的持续发生,但它会崩溃的应用,当它确实发生。
  2. reponseServeur2responseString2从来没有发布过(或自动发布)。这些是内存泄漏
  3. [[reponseServeur2 stringByReplacingOccurrencesOfString:@"\n" withString:@""] mutableCopy];什么也不做。您可能希望将表达式的结果赋值给某个变量。
  4. 您似乎重复了这个序列: self.messageArray = responseString2 JSONValue;messTableView reloadData;这可能只是一个错误。
  5. receive中的一切都是在没有自动发布池的情况下发生的,因此post2dataToSend2request2将泄漏。您报告的警告可能是针对post2的。最低限度,您需要将receive的内容包装在NSAutoreleasePool中,就像displayView一样。
票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/4882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档