1

I have iOS application. There some files in the documents directory. I need to check if these files were edited or replaced. What is the proper way to do it? Shall i some hash of the file or last edited time(how to get this time in iOS) or there is some better way to implement this?

B.S.
  • 21,660
  • 14
  • 87
  • 109
  • 5
    You can surely check with its updated time. Go on to save the updated time to some plist and check it. – Anoop Vaidya Mar 03 '13 at 18:45
  • who else can edit/replace the files in the `Documents` directory in runtime beside your application...? – holex Mar 03 '13 at 18:45
  • 1
    Itunes synchronization, you can add some files to documets directory from itunes – B.S. Mar 03 '13 at 18:47
  • How can i get file edited time? – B.S. Mar 03 '13 at 18:48
  • 2
    @George, in that case try to implement an existing solution for it, like **[this](http://stackoverflow.com/questions/3181821/notification-of-changes-to-the-iphones-documents-directory)** – holex Mar 03 '13 at 19:10

2 Answers2

4

you can use this code to get the file modification date:

NSFileManager* fileManager = [NSFileManager defaultManager];
NSDictionary* attributes = [fileManager attributesOfItemAtPath:path error:nil];

if (attributes != nil) {
    NSDate *date = (NSDate*)[attributes objectForKey:NSFileModificationDate];
    NSLog(@"Last modification date: %@", [date description]);
} else {
    NSLog(@"Not found");
}

here you can find the documentation of the attributesOfItemAtPath:error: function, and here the list of file properties you can get

tkanzakic
  • 5,499
  • 16
  • 34
  • 41
1

Hashing the entire file will work, but is a bit overkill for most purposes. I'd combine a few things which are quick to access:

  • NSFileModificationDate
  • NSFileSize
  • NSFileCreationDate
  • NSFileSystemFileNumber (inode number)

If you are using the NSURL-based API (iOS 4.0+), I'd use

  • NSURLContentModificationDateKey (modification time)
  • NSURLFileSizeKey
  • NSURLCreationDateKey
  • NSURLFileAllocatedSizeKey
  • NSURLAttributeModificationDateKey (st_ctime?)

I'd at least use the the modification time and file size. The other things are things that generally do not change unless the contents change, with a couple of caveats:

  • NSFileSystemFileNumber (the inode number) will likely change if the user restores from a backup.
  • NSURLAttributeModificationDateKey is supposed to change when attributes change. If it is st_ctime (and I'm not entirely sure it is), it is almost guaranteed to catch all changes to the file, but may also catch a lot of changes that don't represent changes to the file contents. I don't know if such changes happen externally (e.g. does iTunes/iCloud backup set attributes as part of the backup process?).
tc.
  • 33,468
  • 5
  • 78
  • 96