2012-09-08 136 views
2

我的程序的一部分讀取目錄,然後計算文件夾中每個文件的散列值。每個文件都加載到內存中,我不知道如何釋放它。我在這裏閱讀了很多主題,但無法找到正確的答案。有人可以幫忙嗎?NSData釋放內存

#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]);  
     } 
    } 
    } 
} 

而且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 
+0

當我使用的NSData * NSData的= [[NSData的頁頭] initWithContentsOfFile:fullFileName]; ... [nsData發佈]或[nsData dealloc] 編譯器告訴我「ARC禁止顯式發送'dealloc'消息」 –

回答

9

如果您的最後一個引用消失後使用ARC則數據將在某個時候被自動釋放。在你的情況下,這將是當它在if語句結束時超出範圍。

總之,您在那裏的代碼是可以的。

有一點,創建數據對象時使用的一些內存可能被保存在autorelease池中。它不會消失,直到你回到事件循環。如果將代碼封裝在@autoreleasepool { ... }塊中,則該問題將消失。

https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html

+0

謝謝,解決我的問題 –