Pregunta

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;
¿Fue útil?

Solución

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"];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top