编写和读取自定义对象到文件IOS

时间:2013-06-05 08:45:23

标签: ios file nskeyedarchiver

我有这个对象。

@interface SeccionItem : NSObject <NSCoding>
{
    NSString * title;
    NSString * texto;
    NSArray * images;
}

@property (nonatomic,strong) NSString * title;
@property (nonatomic,strong) NSString * texto;
@property (nonatomic,strong) NSArray * images;

@end

有了这个实现

@implementation SeccionItem
@synthesize title,texto,images;


- (void) encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:title forKey:@"title"];
    [encoder encodeObject:texto forKey:@"texto"];
    [encoder encodeObject:images forKey:@"images"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    title = [decoder decodeObjectForKey:@"title"];
    texto = [decoder decodeObjectForKey:@"texto"];
    images = [decoder decodeObjectForKey:@"images"];
    return self;
}

@end

我想将填充此对象的数组保存到磁盘上的文件中。

我这样做:

[NSKeyedArchiver archiveRootObject:arr toFile:file];

阅读

NSArray *entries = [NSKeyedUnarchiver unarchiveObjectWithFile:name];
return entries;

但是readed数组总是空的,我不知道为什么,我有一些问题。

我应该使用什么格式的文件路径? on toFile:?

对象上的NSArray是用NSData对象填充的,所以我可以对它们进行编码吗?

我真的迷失了。

3 个答案:

答案 0 :(得分:3)

查看NSKeyedArchiver的文档,尤其是archiveWithRootObject:toFile:方法。

路径基本上是应存储文件的位置,包括文件名。例如,您可以将数组存储在应用程序Documents文件夹中,文件名称为 Storage 。下面的代码片段很常见:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *docDir = [paths objectAtIndex: 0]; 
NSString* docFile = [docDir stringByAppendingPathComponent: @"Storage"];

使用方法 NSSearchPathForDirectoriesInDomains 而不是绝对路径,因为Apple可以根据需要更改Documents文件夹路径。

您可以使用上面的docFile字符串提供给archiveWithRootObject:toFile:方法的toFile参数。

答案 1 :(得分:1)

使用以下方法保存数据

-(NSString*)saveFilePath    {

        NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathString = [[pathArray objectAtIndex:0] stringByAppendingPathComponent:@"data"];
        //NSString *pathString = [[NSBundle mainBundle]pathForResource:@"Profile" ofType:@"plist"];
        return pathString;

    }

-(void)saveProfile  {
    SeccionItem *data = [[SeccionItem alloc]init]
    data. title = @"title";
    data. texto = @"fdgdf";
    data.images = [NSArray arrayWithObjects:@"dfds", nil];


    NSMutableData *pData = [[NSMutableData alloc]init];

    NSString *path = [self saveFilePath];

    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:pData];
    [data encodeWithCoder:archiver];
    [archiver finishEncoding];
    [pData writeToFile:path atomically:YES];

}

使用以下方法加载数据

-(void)loadData {

    NSString* path = [self saveFilePath];
    //NSLog(path);
    NSMutableData *pData = [[NSMutableData alloc]initWithContentsOfFile:path];

    NSKeyedUnarchiver *unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:pData];
    data = [[SeccionItem alloc]initWithCoder:unArchiver];
    //NSLog(@"%@",data.firstName);
    [unArchiver finishDecoding];

}

答案 2 :(得分:0)

对于那些在swift中寻求解决方案的人,我能够按如下方式编写和读取字典到文件系统:

<强>写:

let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)  
do {
    try data.write(to: destinationPath)
} catch let error {
    print("\(error.localizedDescription)")
}

<强>读:

do
{
    let data = try Data.init(contentsOf: path)
    // path e.g. file:///private/var/ .... /Documents/folder/filename
    if let dict = NSKeyedUnarchiver.unarchiveObject(with: data){
        return dict                 
    }
}
catch let error
{
    print("\(error.localizedDescription)")
}