Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File's AccessDate not altered after reading the File by [NSData dataWithContentsOfURL:...]

Tags:

nsurl

I am caching some User Info in file system. And then reading using

NSData *cachedMessagesData = [NSData dataWithContentsOfURL:fileDirectoryForUserInfoCache];

I need to know access time of each cached file, however, when I was checking the access time using the Property key:

NSArray *filesInUserInfoCacheDirectory = [self.fileManager contentsOfDirectoryAtURL:self.cacheDirectoryForUserInfo includingPropertiesForKeys:[NSArray arrayWithObjects:@"NSURLCreationDateKey", @"NSURLContentAccessDateKey", nil] options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];

NSDate *accessDate = [[[filesInUserInfoCacheDirectory lastObject] resourceValuesForKeys:[NSArray arrayWithObject:@"NSURLContentAccessDateKey"] error:nil] objectForKey:@"NSURLContentAccessDateKey"];

I found that the access date is the same as the file creation date. Reading the File through [NSData dataWithContentOfURL:...] wouldn't change the access time property of the file.

Could anyone please tell me why? Is there a way to read the file to make the access time updated? Thanks a lot in advance.

like image 695
John Avatar asked Aug 27 '12 19:08

John


1 Answers

Answering to my own question. I finally had to work around a little bit. Access date attribute of an NSURL file cannot be updated after reading a file, it's date is always the same as the creation date of the NSURL file. One way to work around is to overwrite the file every time after reading, then the access date is updated. But this sounds weird to me.

The other way is to use the Modification Date attribute of an NSURL file instead. This attribute can be set by FileManager's API setAttributes: ofItemAtPath: . Instead of actually modifying the file, I set the modification date attribute every time after reading the file. And then read back this NSDate object by NSURL API resourceValuesForKeys: later on.

[self.fileManager setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate] ofItemAtPath:[fileDirectoryForUserInfoCache path] error:nil]; 
like image 79
John Avatar answered Nov 14 '22 23:11

John