How to delete old files from document directory in objective-c? [closed]
I would like to delete old files (15 days or older) from the user's ~documents
directory in objective-c. Is there a way to know when a file was created and subsequently delete them?
I don't completely understand your question, but I'm going to assume you want a way for a Mac application to identify old files and delete them. If so, try this:
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *files = [fileManager contentsOfDirectoryAtPath:@"/samplePath/" error:NULL];
for (NSString *path in files) {
BOOL isDir;
if ([fileManager fileExistsAtPath:path isDirectory:&isDir] && !isDir) {
NSDictionary *attr = [fileManager attributesOfItemAtPath:path error:NULL];
NSDate *modDate = [attr objectForKey:NSFileModificationDate];
//Do date math
}
}
That will get a date for each date in a directory (just substitute the string @"/samplePath"
with an actual path). Then, you can do the date math to find how long ago it was modified. Alternatively, you could replace NSFileModificationDate
with NSFileCreationDate
to get when the files were created.
精彩评论