Reputation: 2672
I am new to iPhone objectiveC development. I am getting memory leaks when I run the following method.
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
return [documentsDir stringByAppendingPathComponent:@"dbname.sqlite"];
}
and I have found that if I trim it down to just the following... it still leaks
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
return nil;
}
so i tried releasing the paths variable with the following, which still leaks memory.
- (NSString *) getDBPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
[paths release];
return nil;
}
To detect the leak, I am running it in the profiler with the following loop:
for (int iLoop = 0; iLoop < 30; iLoop++) {
NSString *dbPath = [self getDBPath];
[dbPath release];
sleep(1);
}
The amount of memory associated with NSPathStore2 and NSArrayM continues to grow.
Any suggestions on what I a might be doing wrong? thanks!
Upvotes: 1
Views: 1620
Reputation: 7782
Your code for getDBPath is fine, but it is probably called from a context without any autorelease pool.
Fix it by allocating your own pool in the loop code:
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
for (int iLoop = 0; iLoop < 30; iLoop++) {
NSString *dbPath = [self getDBPath];
// [dbPath release]; // do not release! dbPath will be autoreleased
sleep(1);
}
[pool drain];
Upvotes: 1
Reputation: 1862
you should not release an object you dont own. In your case you are trying to deallocate the memory you have not owned. As in the "paths" always refer to the memory allocated and managed by "NSSearchPathForDirectoriesInDomains" . So you shouldnt be deallocating the memory in this case. Make a general rule unless you allocate a memory by your self you shouldnt be calling releasing the memory for every pointer you use in your program. Hope this helps !
Upvotes: 0