Thursday, May 9, 2013

NSDictionary fileModificationDate example ios


Returns the value for the key NSFileModificationDate.
- (NSDate *)fileModificationDate
Return Value
The value for the key NSFileModificationDate, or nil if the dictionary doesn’t have an entry for the key.
Discussion of [NSDictionary fileModificationDate]
This and the other file... methods are for use with a dictionary, such as those returned from the methodsfileAttributesAtPath:traverseLink: (NSFileManager), directoryAttributes(NSDirectoryEnumerator), and fileAttributes (NSDirectoryEnumerator), that represents the POSIX attributes of a file or directory. This method returns the date that the file’s data was last modified.
Example of [NSDictionary fileModificationDate]
- (NSDictionary *) attributesForFile:(NSURL *)anURI {

// note: singleton is not thread-safe
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *aPath = [anURI path];

if (![fileManager fileExistsAtPath:aPath]) return nil;

NSError *attributesRetrievalError = nil;
NSDictionary *attributes = [fileManager attributesOfItemAtPath:aPath

if (!attributes) {
   NSLog(@"Error for file at %@: %@", aPath, attributesRetrievalError);
   return nil;

NSMutableDictionary *returnedDictionary = 
   [NSMutableDictionary dictionaryWithObjectsAndKeys:
        [attributes fileType], @"fileType",
        [attributes fileModificationDate], @"fileModificationDate",
        [attributes fileCreationDate], @"fileCreationDate",
        [NSNumber numberWithUnsignedLongLong:[attributes fileSize]], @"fileSize",

return returnedDictionary;
Example of [NSDictionary fileModificationDate]
NSString *documentsDirectory = [[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
NSArray *docFileList = [[NSFileManager defaultManager] subpathsAtPath:documentsDirectory];
NSEnumerator *docEnumerator = [docFileList objectEnumerator];
NSString *docFilePath;
NSDate *lastModifiedDate = [NSDate dateWithTimeIntervalSince1970:0];
NSString *lastModifiedFilePath = @"";

while ((docFilePath = [docEnumerator nextObject])) {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:docFilePath];
    NSDictionary *fileAttributes = [[NSFileManager defaultManager]  attributesOfItemAtPath:fullPath error:nil];
    NSDate currentModifiedDate = [fileAttributes fileModificationDate];

    if (lastModifiedDate < fileModificationDate) {
        fileModificationDate = lastModifiedDate;
        lastModifiedFilePath = fullPath;

return lastModifiedFilePath;