序列化自定义对象的正确方法

序列化自定义对象的正确方法

本文介绍了在iOS中保存/序列化自定义对象的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义对象,一个 UIImageView 子类,它有一些 gestureRecognizer 对象。

I have a custom object, a UIImageView subclass which has a few gestureRecognizer objects.

如果我有一些这些对象存储在 NSMutableArray 中,那么这个对象数组将如何保存到磁盘,以便当用户再次运行应用程序时可以加载它?

If I have a number of these objects stored in a NSMutableArray, how would this array of objects be saved to disk so that it can be loaded when the user runs the app again?

我想从磁盘加载数组并使用这些对象。

I would like to load the array from the disk and use the objects.

推荐答案

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

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];

这篇关于在iOS中保存/序列化自定义对象的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:32