Is this the right way to create / destroy a line in a loop?

Just wondering if this is the way to do this, I just want to make sure that it does not leak, although I think that I am only modifying the contents of the string.

NSMutableString *newPath = [[NSMutableString alloc] init];

for(fileName in [manager enumeratorAtPath:rootPath]){
    if ([[fileName pathExtension] isEqual:@"exr"]) {
        [fileArray addObject:fileName];

        // THIS BIT 
        [newPath setString:rootPath];
        [newPath appendString:@"/"];
        [newPath appendString:fileName];
        // HERE
        attrDir = [manager attributesOfItemAtPath:newPath error:&myError];

        fileSize = [attrDir objectForKey: @"NSFileSize"];
        NSLog(@"File: /%@ Size: %@", fileName, fileSize);
    }
}
[newPath release];

Gary

+3
source share
3 answers

It looks good. If you are using Xcode 3.2, you can Build-> Build and Analyzer to force Clang to check such things.

Remember that you only need to free the things that you assign, new, copy or save.

Consider using stringByAppendingPathComponent, rather than hardcoding, a path separator @"/". NSString has a number of methods like this specifically for working with paths.

NSString* fullPath = [rootPath stringByAppendingPathComponent:fileName];
+7

, initWithFormat :

NSString *newPath = [[NSString alloc] initWithFormat:@"%@/%@",rootPath,fileName];

// do your thing

[newPath release];
+1

, .

But this can be done with even less code consumption and memory management:

for(fileName in [manager enumeratorAtPath:rootPath]){
  if ([[fileName pathExtension] isEqualToString:@"exr"]) {
    [fileArray addObject:fileName];

    NSString* newPath = [rootPath stringByAppendingPathComponent:fileName];
    attrDir = [manager attributesOfItemAtPath:newPath error:&myError];

    fileSize = [attrDir objectForKey: @"NSFileSize"];
    NSLog(@"File: /%@ Size: %@", fileName, fileSize);
  }
}
+1
source

Source: https://habr.com/ru/post/1718741/


All Articles