【问题标题】:Error message is saying my data is NULL - NSKeyedUnArchiver - I've followed all the steps - still won't work错误消息说我的数据为 NULL - NSKeyedUnArchiver - 我已按照所有步骤操作 - 仍然无法工作
【发布时间】:2014-12-30 00:41:58
【问题描述】:

我想将 NSMutableArray *allRedItems 保存到文件中。它包含自定义对象,Itemz:

@interface Itemz : NSObject <NSCoding>
@property double price;
@property double quality;
@property double style;


@property double overallAverage;

到目前为止,我已经完成了所有正确的步骤:

@implementation Itemz

- (void)encodeWithCoder:(NSCoder *)encoder {


[encoder encodeDouble:self.price forKey:@"price"];
[encoder encodeDouble:self.style forKey:@"style"];
[encoder encodeDouble:self.quality forKey:@"quality"];
[encoder encodeDouble:self.overallAverage forKey:@"overallAverage"];

[encoder encodeBool: self.isClicked forKey:@"isClicked"];
}

- (id)initWithCoder:(NSCoder *)decoder {
if((self = [super init])) {
    //decode properties, other class vars
    self.price = [decoder decodeDoubleForKey:@"price"];

    self.style = [decoder decodeDoubleForKey:@"style"];
    self.quality = [decoder decodeDoubleForKey:@"quality"];
    self.overallAverage = [decoder decodeDoubleForKey:@"overallAverage"];
    self.isClicked = [decoder decodeBoolForKey:@"isClicked"];


}
return self;
}
@end

这是我保存数组 *allRedItems 的地方

@implementation AllRedItems
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.allRedItems];

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *allItemsRed = [documentsDirectory  stringByAppendingPathComponent:@"allItemsRed"];

[data writeToFile:allItemsRed atomically:YES];
 @end  

当我检索它时,它给了我这个错误 - [NSKeyedUnarchiver initForReadingWithData:]: data is NULL

@implementation ItemSuggestion
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * path = [documentsDirectory stringByAppendingPathComponent:@"allItemsRed"];
NSData * data = [NSData dataWithContentsOfFile:path];
NSMutableArray *allRedItems = [NSKeyedUnarchiver unarchiveObjectWithData:data];
@end

我错过了什么吗?还是我需要添加一些东西?

【问题讨论】:

  • 除其他外,您忽略了编译和执行之间的区别。
  • 对不起,我是新手,我收到的错误消息是 [NSKeyedUnarchiver initForReadingWithData:]: data is NULL 。我缺少的“其他东西”是什么?我对你的说法感到困惑

标签: objective-c nsmutablearray nsdata archive nskeyedarchiver


【解决方案1】:

你把它保存在NSDocumentationDirectory

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);

但是从NSDocumentDirectory找回,所以你拿不到。

NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

在这两种方法中使用NSDocumentDirectory

【讨论】:

    猜你喜欢
    • 2020-09-19
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 2020-08-20
    • 2013-03-29
    • 1970-01-01
    相关资源
    最近更新 更多