简体   繁体   English

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

[英]Writing and reading custom object to file IOS

i have this object. 我有这个对象。

@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

With this implementation 通过此实现

@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

I want to save an array filled with this objects to a file on disk. 我想将填充有该对象的数组保存到磁盘上的文件中。

Im doing this: 我正在这样做:

to write 来写

[NSKeyedArchiver archiveRootObject:arr toFile:file];

to read 读书

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

But the readed array is always empty, i dont know why, i have some questions. 但是读取的数组总是空的,我不知道为什么,我有一些问题。

What format should i use for file path? 我应该使用哪种格式的文件路径? on toFile:? 上toFile :?

The NSArray on the object is filled with NSData objects, so i can encode them? 对象上的NSArray充满了NSData对象,因此我可以对它们进行编码?

Im really lost on this. 我真的迷失了这一点。

Take a look at the documentation of NSKeyedArchiver, especially the archiveWithRootObject:toFile: method. 查看NSKeyedArchiver的文档,尤其是archiveWithRootObject:toFile:方法。

The path is basically where the file should be stored including the file name. 路径基本上是文件应存储的位置,包括文件名。 For example you can store your array in your app Documents folder with file name called Storage . 例如,您可以将数组存储在应用程序的Documents文件夹中,文件名为Storage The code snippet below is quite common: 下面的代码段很常见:

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

The method NSSearchPathForDirectoriesInDomains is used instead of absolute path because Apple can be changing the Documents folder path as they want it. 使用方法NSSearchPathForDirectoriesInDomains而不是绝对路径,因为Apple可以根据需要更改Documents文件夹路径。

You can use the docFile string above to be supplied to the toFile parameter of the archiveWithRootObject:toFile: method. 您可以使用上面的docFile字符串提供给archiveWithRootObject:toFile:方法的toFile参数。

Use the following method to save data 使用以下方法保存数据

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

}

Use the following method to load data 使用以下方法加载数据

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

}

For those who are seeking the solution in swift, I was able to write and read dictionary to file system as follows : 对于那些正在迅速寻求解决方案的人,我能够按照以下方式编写和读取字典到文件系统:

Write: 写:

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

Read: 读:

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)")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM