自定义objective-c类不编码

时间:2013-10-17 15:47:18

标签: objective-c serialization encoding nscoding

我有一个符合NSCoding协议的自定义类,但在调用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;
}

如您所见,变量map是一个包含字符串的多维数组。不确定这是不是搞乱了什么。

我的界面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;

1 个答案:

答案 0 :(得分:0)

假设您尝试使用writeToFile:atomically:

写入文件

NSCoding创建一个不能与writeToFile:atomically:一起使用的序列化存档。您需要使用NSKeyedArchiver,如下所示:

[NSKeyedArchiver archiveRootObject:levelObject toFile:@"path/level-object.txt"];