views:

123

answers:

2

I'm writing an iPhone app that is mainly centered around grid patterns, so I have a Pattern class which contains an NSMutableArray of NSMutableArrays. This class implements NSCoding, and it seems the following code works just fine in my iPhone app:

GridPattern * pattern = [GridPattern patternWithWidth:8 height:8];
[pattern setValueAtColumn:0 row:7 value:1];
[NSKeyedArchiver archiveRootObject:pattern toFile:@"test.pat"];
pattern = [NSKeyedUnarchiver unarchiveObjectWithFile:@"test.pat"];

If I debug the code above, I find after stepping over line 4, that I have a GridPattern object with the appropriate value set for column 0, row 7.

I have also written a Cocoa OSX application intended for creating patterns for the iPhone app, which also uses the same GridPattern class. It can also load and save the patterns successfully.

What I wanted to do was:

  • create and save the patterns in the OS X app
  • add the pattern files into Resources group in XCode for the iPhone app; (I added it as test.pat)
  • unarchive the patterns in my iPhone app, using code such as:

    pattern = [NSKeyedUnarchiver unarchiveObjectWithFile:@"test.pat"];

However, when I try to unarchive the objects from this file, all that is returned is nil. I thought I might have had the file path wrong and also tried @"Resources/test.pat" to no avail.

Am I simply referring to the file incorrectly? Or are archived objects simply not cross-platform? Is this whole approach just plain wrong? If so, how would you do it?

+3  A: 

I don't know about the compatibility of archiving across platforms, but to refer to a bundle resource, you should always use NSBundle to find it. Don't depend on the current path.

Chuck
Thanks, Chuck! You hit the nail on the head. So for those who were curious, archived objects do seem to work across platforms. I used the following code which worked: pattern = [NSKeyedUnarchiver unarchiveObjectWithFile:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"pat"]];
SamCee
+1  A: 

As your model is just an array of arrays, you could use XML property lists which do work across architectures.

Graham Lee
I do exactly this (save property lists on OS X and read them on the iPhone) in one of my applications.
Mark Bessey