保存的NSMutableArray到磁盘

保存的NSMutableArray到磁盘

本文介绍了保存的NSMutableArray到磁盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSMutableArray保存类型Person的对象(NSString的,的NSString,INT)
我正在寻找一种简单的方法来保存这个数组到光盘以后重新装入。

I have an NSMutableArray that holds objects of the type Person (NSString,NSString,int)I am looking for a easy way to save this array to disc and load it again later.

我很多了解序列化,但我从来没有这样做。也许这不是最简单的方法,我毕竟。

I read alot about serialization but I never have done that. Maybe it's not the easiest way for me after all.

推荐答案

第一步是让你的Person类实现NSCoding协议。其基本战略是实现两个方法序列化和非序列化对象的每个实例变量要会话之间持续。

The first step is to make your Person class implement the NSCoding protocol. The basic strategy is to implement two methods to serialize and un-serialize each of the object's instance variables that you want to persist between sessions.

#pragma mark NSCoding Protocol

- (void)encodeWithCoder:(NSCoder *)encoder;
{
    [encoder encodeObject:[self foo] forKey:@"foo"];
    [encoder encodeDouble:[self bar] forKey:@"bar"];
}

- (id)initWithCoder:(NSCoder *)decoder;
{
    if ( ![super init] )
    	return nil;

    [self setFoo:[decoder decodeObjectForKey:@"foo"]];
    [self setBar:[decoder decodeDoubleForKey:@"bar"]];

    return self;
}

要实际写入的对象到磁盘,你可以使用NSArray的将writeToFile:的方法,或者如果你想更明确的了解它是如何做使用NSKeyedUnarchiver类。在这两种情况下,您也可以把您的阵列到另一个数据结构(字典的例子),如果你想在你的数据文件中的其他项目(如文件格式数字)。

To actually write the objects to disk, you could use NSArray's writeToFile: method, or use the NSKeyedUnarchiver class if you want to be more explicit about how it's done. In both cases you can also put your array into another data structure (a dictionary for example) if you want to include other items (such as a file format number) in your data file.

这篇关于保存的NSMutableArray到磁盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:57