Memory leak : How to stop?

倖福魔咒の 提交于 2019-12-11 07:15:50

问题


I am using NSObject class to get all the data from a database. When I call that function it will show a memory leak where I assign a string using stringWithFormat. I think when we use this method we should not have to release that string so why does it show a memory leak?

Thanks in advance. :)

- (void) Allnote
{
   [app.NoteArray removeAllObjects];
   NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Notes.sqlite"];
   if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) 
   {
      NSString *querySQL = [NSString stringWithFormat:@"SELECT * From note" ];
      const char *sql = [querySQL UTF8String];
      sqlite3_stmt *searchStatement;

    if (sqlite3_prepare_v2(database, sql, -1, &searchStatement, NULL) == SQLITE_OK) 
    {
        while (sqlite3_step(searchStatement) == SQLITE_ROW) 
        {
            noteClass *noteObj = [[noteClass alloc]init];

            noteObj.noteTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)];   // at this place
            noteObj.noteContent = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 1)]; // at this place

            NSNumber *noteId = [NSNumber numberWithInt:sqlite3_column_int(searchStatement, 2)];

            noteObj.noteId = [NSString stringWithFormat:(@"%@"),noteId]; // at this place

            files=noteObj.noteTitle;
            filescont=noteObj.noteContent;
            [app.NoteArray addObject:noteObj];
            [noteObj release];

        }
    }
    sqlite3_finalize(searchStatement);

}

sqlite3_close(database);
}

回答1:


See, stringWithFormatis a factory method means that it has autorelease in its definition, that's why u r getting memory issue. But, that is not an issue.its 100% perfect.




回答2:


If you aren't apply a format, then why use stringWithFormat

NSString *querySQL = [NSString stringWithFormat:@"SELECT * From note" ];

Is the same as:

NSString *querySQL = @"SELECT * From note";

And you are correct, you do not have te release them.




回答3:


I am responding in addition to Surya Kant's answer.

It was not a problem with that. But still if you want to avert the issue, please do onething.

Instead of the following line,

noteObj.noteTitle = [NSString stringWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)];   // at this place

do as follows

NSString *noteTit = [[NSString alloc] initWithUTF8String:(char *)sqlite3_column_text(searchStatement, 0)];
noteObj.noteTitle = noteTit;
[noteTit release];

Similarly do it for others.



来源:https://stackoverflow.com/questions/8166915/memory-leak-how-to-stop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!