简体   繁体   English

在仪器中查找内存泄漏的原因

[英]Finding the cause of memory leak in Instruments

I have run the leaks in Instruments and it is showing me a memory leak with a 100% value. 我已经在Instruments中运行了泄漏,它向我显示了100%值的内存泄漏。 I am able to see the line of code that is causing the problem. 我能够看到导致问题的代码行。 But not really sure what the error is.. 但不是很确定错误是什么..

- (void) listAllBooks {
    if (marrListFromDB != nil) {
        [marrListFromDB removeAllObjects];
        marrListFromDB = nil;
    }

    marrListFromDB = [[NSMutableArray alloc] init];
    ServerCommunicationAPI *servApi = [[ServerCommunicationAPI alloc] init];
    servApi.delegate = self;
    NSURL *url = [NSURL URLWithString:kLISTCONTENTS];
    [servApi listBooksWithDeviceID:singleton.g_strdevID deviceKey:singleton.g_strdevID andSessionString:singleton.g_strSessionID sessionKey:@"sessionKey" URL:url andRequestMethod:@"POST"];
}

The line of error is the last one. 错误线是最后一条。 Not sure why it is causing a memory leak... Need some guidance.. 不知道为什么会导致内存泄漏...需要一些指导。

It is hard to tell from the information provided, but maybe the delegate property of ServerCommunicationAPI is declared as (strong) ? 从所提供的信息很难分辨,但也许ServerCommunicationAPI属性被声明为(strong) In this case servApi could never be released, because it keeps a strong reference to itself (retain cycle). 在这种情况下, servApi永远不会被释放,因为它对自身有很强的引用(保留周期)。
I suggest that you check in instruments which kind of object leaks, this would make the answer much easier. 我建议您检查仪器中哪种对象泄漏,这将使答案容易得多。

Try out this. 试试这个。 May it resolve your memory leak problem. 可以解决您的内存泄漏问题。

- (void) listAllBooks {
if (marrListFromDB != nil) {
    [marrListFromDB removeAllObjects];
    marrListFromDB = nil;
}
ServerCommunicationAPI *servApi ;
marrListFromDB = [[NSMutableArray alloc] init];
if(servApi == nil){

     ServerCommunicationAPI *servApi = [[ServerCommunicationAPI alloc] init];
}//Every time it going to alloc. It's strong object may be due do this memory leak happens. 
servApi.delegate = self;
NSURL *url = [NSURL URLWithString:kLISTCONTENTS];
[servApi listBooksWithDeviceID:singleton.g_strdevID deviceKey:singleton.g_strdevID andSessionString:singleton.g_strSessionID sessionKey:@"sessionKey" URL:url andRequestMethod:@"POST"];

} }

Just another idea: Maybe you execute your code in a separate thread for which no autorelease pool has been set up? 另一个想法:也许您在没有设置自动释放池的单独线程中执行代码? In this case the message sent to servApi could create autorelease objects that cannot be released later since no autorelease pool exists. 在这种情况下,发送到servApi的消息可能会创建自动释放对象,这些对象以后将无法释放,因为不存在自动释放池。
So, if your code is not executed in the main thread, please check if an autorelease pool has been set up using a @autoreleasepool {...} block for your thread. 因此,如果您的代码未在主线程中执行,请检查是否已使用@autoreleasepool {...}块为您的线程设置了自动释放池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM