Search code examples
databaseipadmemory-leaksstringwithformat

Memory leak : How to stop?


You can see that memory leak error 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);
}

Solution

  • 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.