views:

357

answers:

4

Hi there!

I have two xml files (a.xml and b.xml) in my file system (iPhone). Now I want to know if these files contain exactly the same data. Most of the time, this comparison would be true, because b.xml is the result of a copyItemAtPath: operation. Unless it is overwritten by newer information. What would be the most efficient way to compare these files?

  1. I could read the contents of the files as strings and then compare the strings
  2. I could parse the files and compare some key elements
  3. I guess there is a very blunt way, that doesn't need to interpret the file, but allows me to compare on a lower level.

Any suggestion is very welcome.

Thanks ahead

Sjakelien

Update:

I ended up doing this:

oldData = [NSData dataWithContentsOfFile:PathToAXML];
newData = [NSData dataWithContentsOfFile:PathToBXML];

and then compare it with:

[newData isEqualToData:oldData];

The question is still: is that more efficient than:

oldData = [NSString dataWithContentsOfFile:PathToAXML];
newData = [NSString dataWithContentsOfFile:PathToBXML];

[newData isEqualToString:oldData];
+3  A: 

One alternative to comparing the file contents is to track the file modification date -- if it's later than the date you created the copy, you might assume that it has been updated.

See fileAttributesAtPath:traverseLink: in the NSFileManager class.

Daniel Dickison
That is a way to do it. And quite efficient as well, I guess. I will need to store that somewhere though.
Sjakelien
This is a good alternative IMO.
Troggy
You don't have to store the date somewhere else if you preserve it when doing the copy. I think NSFileManager can do this.
Nikolai Ruhe
A: 

This is a good start to getting a solution that matches your requirements: Coccoa xml parsing

ennuikiller
I know how to parse XML. I think it's just not too efficient in this case. And pretty cumbersome.
Sjakelien
+1  A: 
BOOL filesAreEqual = [[NSData dataWithContentsOfMappedFile:file1] isEqual:[NSData dataWithContentsOfMappedFile:file2]];
Nikolai Ruhe
Looks interesting. I'll give it a try.
Sjakelien
+2  A: 

Is there a reason you don't want to do something like an MD5 hash of the two files and compare the results - here is an example of some code that seems pretty common

http://stackoverflow.com/questions/840386/gravatar-for-iphone-how-do-i-generate-a-hexadecimal-md5-hash

Joel Schlundt