Reputation: 865
Part of my program reads directory, then calculates hash for each file in folder. Each file loads to memory and I don`t know how to release it. I read a lot of topics here but can not find right answer. Could someone help?
#import "MD5.h"
...
NSFileManager * fileMan = [[NSFileManager alloc] init];
NSArray * files = [fileMan subpathsOfDirectoryAtPath:fullPath error:nil];
if (files)
{
for(int index=0;index<files.count;index++)
{
NSString * file = [files objectAtIndex:index];
NSString * fullFileName = [fullPath stringByAppendingString:file];
if( [[file pathExtension] compare: @"JPG"] == NSOrderedSame )
{
NSData * nsData = [NSData dataWithContentsOfFile:fullFileName];
if (nsData)
{
[names addObject:[NSString stringWithString:[nsData MD5]]];
NSLog(@"%@", [nsData MD5]);
}
}
}
}
And MD5.m
#import <CommonCrypto/CommonDigest.h>
@implementation NSData(MD5)
- (NSString*)MD5
{
// Create byte array of unsigned chars
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
// Create 16 byte MD5 hash value, store in buffer
CC_MD5(self.bytes, (uint)self.length, md5Buffer);
// Convert unsigned char buffer to NSString of hex values
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
@end
Upvotes: 2
Views: 7552
Reputation: 86651
If you are using ARC then the data will be automatically deallocated at some point after the last reference to it goes away. In your case this will be when it goes out of scope at the end of the if statement.
In short, the code you have there is OK.
There is one thing, some of the memory used when creating the data object might be held in an autorelease pool. It won't go away until you are back in the event loop. If you wrap the code in an @autoreleasepool { ... }
block, that problem will go away.
Upvotes: 9