0

I have a custom class that conforms to the NSCoding protocol but still refuses to encode when I call write to file.

@implementation PXLevel

- (id)initWithName:(NSString *)name andArray:(NSMutableArray *)map {
    self = [super init];
    self.name = name;
    self.map = map;
    return self;
}

- (id)initWithName:(NSString *)name {
    self = [super init];
    self.name = name;

    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 8; i++) {
        NSMutableArray *line = [[NSMutableArray alloc] init];
        for (int j = 0; j < 8; j++) {
            [line addObject:@"grass"];
        }
        [tempArray addObject:line];
    }
    self.map = tempArray;
    return self;
}

-(void) encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.name forKey:@"levelName"];
    [aCoder encodeObject:self.map forKey:@"levelMap"];
}

-(id) initWithCoder:(NSCoder *)aDecoder
{
    if((self = [super init]))
    {
        self.name = [aDecoder decodeObjectForKey:@"levelName"];
        self.map = [[aDecoder decodeObjectForKey:@"levelMap"] mutableCopy];

    }

    return self;
}

As you can see, variable map is a multidimensional array with strings in it. Not sure if this is messing it up or something.

My interface btw

@interface PXLevel : NSObject <NSCoding>

@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSMutableArray *map;

- (id)initWithName:(NSString *)name andArray:(NSMutableArray *)map;
- (id)initWithName:(NSString *)name;
rmaddy
  • 314,917
  • 42
  • 532
  • 579
evilseto
  • 29
  • 6
  • What object are you calling `writeToFile:` on? How does it relate to your `PXLevel` class? – Tom Harrington Oct 17 '13 at 18:11
  • Specifically, a mutable array of PXLevel objects (implementation above). I checked with code, the method can save an empty array to a new plist but add a PXLevel to it and nothing happens. – evilseto Oct 17 '13 at 22:39

1 Answers1

0

Assuming you are trying to write to file using writeToFile:atomically:

NSCoding creates a serialised archive which cannot be used with writeToFile:atomically:. You need to use NSKeyedArchiver like following:

[NSKeyedArchiver archiveRootObject:levelObject toFile:@"path/level-object.txt"];
nomann
  • 2,257
  • 2
  • 21
  • 24
  • Do you have to archive to a txt file with this method? Also, can this only archive the custom object, because I tried this with a mutable array of PXLevel objects and the data came back not quite right. – evilseto Oct 17 '13 at 22:57
  • Whoops! Forgot to go both ways. Changed my loading method to unarchiveObjectWithFile and now it works! Thanks a lot for your help! – evilseto Oct 17 '13 at 23:05
  • You are welcome. Btw, .txt was just an extension, you can use .archive or custom extension if you want. – nomann Oct 18 '13 at 07:49