Memory leak in String Formatter

605 views Asked by At

I am using Objective C with ARC. I have the following snippet of code, which seems to leak memory due to the string formatter.

Memory leak in stringWithFormat

I changed the stringWithFormat convenience method into the more general alloc init, but it still leaks memory in this line.

Memory leak in initWithFormat

I read here that I should use the copy keyword, but it still leaks memory in this line.

Memory leak with copy property

Now, when I remove the formatter altogether, the code does not leak memory in this line.

No memory leak without formatter

  1. Why is this line causing a memory leak?
  2. How can I solve this memory leak?

Additional information:

  • Code written in: Xcode 6.3.1
  • Memory leaks visualized using: Instruments from Xcode 6.3.1
  • iOS Deployment Target: iOS 5.0

Code base:

#define DATABASE_NAME           @"orderwriter"

+ (SQLiteManager *) getSQLiteManager
{
    // NSInteger userId = [(NSString *)[AppUtil NSDefaultforKey:USER_ID] integerValue];
    // NSString *dbName = [NSString stringWithFormat:@"%@_%ld.db", DATABASE_NAME, (long)userId];
    NSString *dbName = @"orderwriter_58.db";
    SQLiteManager *dbManager = [[SQLiteManager alloc] initWithDatabaseNamed:dbName];
    return dbManager;
}

The class SQLiteManager, I found here on Github.

1

There are 1 answers

2
Duncan C On

The stringWithFormat method returns an autoreleased object. It won't get released until the release pool is drained. Are you running in a background thread by any chance? If so, you may need to create an autorelease pool at the beginning of your thread code and drain it when you are done.

If not then I'm not sure why you would have a leak. ARC should handle the ownership of that string correctly. It's possible that it is a compiler bug. What version of Xcode are you using?

If it's not an autorelease pool issue then you should probably file a radar bug with Apple.