簡體   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