繁体   English   中英

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

[英]Writing and reading custom object to file IOS

我有这个对象。

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

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

我应该使用哪种格式的文件路径? 上toFile :?

对象上的NSArray充满了NSData对象,因此我可以对它们进行编码?

我真的迷失了这一点。

查看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参数。

使用以下方法保存数据

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

}

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

写:

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

暂无
暂无

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

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