简体   繁体   中英

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. 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) ? In this case servApi could never be released, because it keeps a strong reference to itself (retain cycle).
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.
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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