Reputation: 1424
For some reason this method that I have written doesn't get rid of the oldest file in a directory even though everything seems fine from a logic point of view. Is there something subtle I am missing?
+(void)removeOldestFileFromDir:(NSURL *)dir forFileManager:(NSFileManager *)fm{
NSError *error = nil;
NSArray *contents = [fm contentsOfDirectoryAtPath:[dir path] error:&error];
NSArray *jpgFiles = [contents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.jpg'"]];
NSDate *oldest = [NSDate date];
NSString *oldestFileName = nil;
for (NSString *f in jpgFiles) {
NSString *photoPath = [[dir path] stringByAppendingPathComponent:f];
NSDate *created = [[fm attributesOfItemAtPath:photoPath error:&error] objectForKey:@"NSFileCreationDate"];
if([created compare:oldest] == NSOrderedAscending){
oldestFileName = [NSString stringWithString:photoPath];
}
}
[fm removeItemAtPath:oldestFileName error:&error];
}
I've checked the error and it's alway (null) and the file that gets deleting is seemingly random - sometimes it's the newest, sometimes it's another one.
Upvotes: 0
Views: 751
Reputation: 23268
You forget to set oldest variable inside of your if.
It should be like that:
if([created compare:oldest] == NSOrderedAscending){
oldestFileName = [NSString stringWithString:photoPath];
oldest = created; // !!! This is what is missing
}
Upvotes: 3