0
votes

This might be a stupid question, but I'm struggling with some odd memory increase in a loop. So I thought I might have an understanding problem with ARC.

Say, I have a function like this:

+(NSString *)getDocPathToFile:(NSString *)filename{

NSFileManager *fileManager = [NSFileManager defaultManager];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:fn];

    return path;
}

Now, what happens with the instantiated vars like fileManager, paths, documentsDirectory and path? Are they destroyed after the value gets returned and thus, don't take up any memory?

To explain this a little further: I'm calling this method a couple of times in a loop. Now, in instruments, I can see a constant memory increase in CFString (immutable) but I fail in tracking down where that CFString is allocated (I'm not using any CoreFoundation-stuff, as far as I'm aware). I'm not sure whether the above function is the culprit, might be something completely different...

Thanks for enlightening me... ;)

1
Your variables are actually weak. After the end of that function will get released by ARC. The function itself will create a new instance of an NSString that you going to assign to a variable. The memory will remain retained until nothing points to that new string anymore.Astri
Great, thanks for the clarification...Swissdude

1 Answers

0
votes

you can use @autoreleasepool to reduce memory watermark level

e.g.

for (/**/) // some loop
{
    @autoreleasepool
    {
        // some code inside loop
    }
}

or you can put @autoreleasepool inside your method

+(NSString *)getDocPathToFile:(NSString *)filename{
    @autoreleasepool {
        NSFileManager *fileManager = [NSFileManager defaultManager];

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *path = [documentsDirectory stringByAppendingPathComponent:fn];

        return path;
    }
}