且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在iOS中保存/序列化自定义对象的正确方法

更新时间:2022-11-19 08:44:18

我对以下内容的实现如下并且完美无缺:

My implementation for something similar is the following and works perfectly :

自定义对象(设置)应该实现协议NSCoding:

The custom object (Settings) should implement the protocol NSCoding :

-(void)encodeWithCoder:(NSCoder *)encoder{
    [encoder encodeObject:self.difficulty forKey:@"difficulty"];
    [encoder encodeObject:self.language forKey:@"language"];
    [encoder encodeObject:self.category forKey:@"category"];
    [encoder encodeObject:self.playerType forKey:@"playerType"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.difficulty = [decoder decodeObjectForKey:@"difficulty"];
        self.language = [decoder decodeObjectForKey:@"language"];
        self.category = [decoder decodeObjectForKey:@"category"];
        self.playerType = [decoder decodeObjectForKey:@"playerType"];
    }
    return self;
}

以下代码将自定义对象写入文件(set.txt)和然后将其恢复到数组myArray:

The following code writes the custom object to a file (set.txt) and then restores it to the array myArray :

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"set.txt"];

NSMutableArray *myObject=[NSMutableArray array];
[myObject addObject:self.settings];    

[NSKeyedArchiver archiveRootObject:myObject toFile:appFile]; 

NSMutableArray* myArray = [NSKeyedUnarchiver unarchiveObjectWithFile:appFile];