【问题标题】:Failing to set / retrieve data using NSKeyedArchiver / NSKeyedUnarchiver on file无法使用文件上的 NSKeyedArchiver / NSKeyedUnarchiver 设置/检索数据
【发布时间】:2016-05-14 04:45:24
【问题描述】:

我正在尝试使用 NSKeyedArchiver 在 iOS 应用程序上保存一些持久性数据以写入文件,我想稍后使用 NSKeyedUnarchiver 检索这些数据。我创建了一个非常基本的应用程序来测试一些代码,但没有成功。 以下是我正在使用的方法:

- (void)viewDidLoad
{
    [super viewDidLoad];

    Note *myNote = [self loadNote];

    myNote.author = @"MY NAME";

    [self saveNote:myNote]; // Trying to save this note containing author's name

    myNote = [self loadNote]; // Trying to retrieve the note saved to the file

    NSLog(@"%@", myNote.author); // Always logs (null) after loading data
}

-(NSString *)filePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent: @"myFile"];
    return filePath;
}

-(void)saveNote:(Note*)note
{
    bool success = [NSKeyedArchiver archiveRootObject:note toFile:[self filePath]];
    NSLog(@"%i", success); // This line logs 1 (success)
}

-(Note *)loadNote
{
    return [NSKeyedUnarchiver unarchiveObjectWithFile:[self filePath]];
}

我用来测试这段代码的类如下:

注意.h

#import <Foundation/Foundation.h>

@interface Note : NSObject <NSCoding>

@property NSString *title;
@property NSString *author;
@property bool published;

@end

注意.m

#import "Note.h"

@implementation Note

-(id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init])
    {
        self.title = [aDecoder decodeObjectForKey:@"title"];
        self.author = [aDecoder decodeObjectForKey:@"author"];
        self.published = [aDecoder decodeBoolForKey:@"published"];
    }
    return self;
}

-(void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.title forKey:@"title"];
    [aCoder encodeObject:self.author forKey:@"author"];
    [aCoder encodeBool:self.published forKey:@"published"];
}

@end

我已经看到使用 NSUserDefaults (https://blog.soff.es/archiving-objective-c-objects-with-nscoding) 的类似示例,但我想将此数据保存到文件中,因为据我所知,NSUserDefaults 主要用于存储用户偏好,而不是一般数据。我错过了什么吗?提前致谢。

【问题讨论】:

    标签: ios objective-c nskeyedarchiver nskeyedunarchiver


    【解决方案1】:

    想想当您的应用第一次运行并调用 loadNote: 方法时会发生什么,但尚未保存任何内容。

    行:

    Note *myNote = [self loadNote];
    

    将导致myNote 成为nil,因为没有加载任何内容。现在想想它是如何在你的其余代码中级联的。

    您需要处理这种没有保存数据的初始情况。

    Note *myNote = [self loadNote];
    if (!myNote) {
        myNote = [[Note alloc] init];
        // Setup the initial note as needed
        myNote.title = ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-01-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-10
      • 1970-01-01
      • 1970-01-01
      • 2013-05-08
      • 2018-12-05
      相关资源
      最近更新 更多