如何从iPhone的文档目录中删除超过两天的文件

问题描述:

我有一个可以记录声音文件并将其存储在应用程序文档目录中的应用程序.

I have an App in which I record the sound files and store it in apps Document Directory.

我想要的是,它应该只包含昨天和几天以前的旧文件,并从iPhone应用程序的文件夹中删除所有其他文件.有什么办法吗?

What I want is, it should contain only yesterday and to days older files and remove all others from the folder in iPhone app. Is there any way to do this?

谢谢..

请查看以下代码.

//Get the Document directory path.
 #define kDOCSFOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]

//Delete files by iterating items of the folder.
NSFileManager* fm = [[[NSFileManager alloc] init] autorelease];
NSDirectoryEnumerator* en = [fm enumeratorAtPath:kDOCSFOLDER];    
NSError* err = nil;
BOOL res;

NSString* file;
while (file = [en nextObject]) {
            // Date comparison.
    NSDate   *creationDate = [[fm attributesOfItemAtPath:file error:nil] fileCreationDate];
    NSDate *yesterDay = [[NSDate date] dateByAddingTimeInterval:(-1*24*60*60)];

    if ([creationDate compare:yesterDay] == NSOrderedAscending)
    {
        // creation date is before the Yesterday date
        res = [fm removeItemAtPath:[kDOCSFOLDER stringByAppendingPathComponent:file] error:&err];

        if (!res && err) {
            NSLog(@"oops: %@", err);
        }

    }

}