【发布时间】:2011-12-14 10:58:12
【问题描述】:
我正在使用 NSURLConnection 从服务器获取 XML 数据。我正在解析数据并将其显示在表格视图中。这一切都按预期工作。现在,我想保存下载的数据以供离线使用。想法是获取下载的 NSData,将其转换为 NSArray 并将其存储到 NSUserDefaults 或单独的文件中。但是,我在将 NSData 转换为 NSArray 时遇到问题。
我将逻辑添加到(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 方法。我正在尝试做的事情如下:
NSError *error;
NSPropertyListFormat plistFormat;
id object = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListImmutable format:&plistFormat error:&error];
if (error != nil) {
NSLog(@"Error %@", [error localizedDescription]);
[error release];
}
if ([object isKindOfClass:[NSArray class]]) {
NSLog(@"IS Array");
NSArray *objectArray = object;
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:objectArray] forKey:@"myKey"];
} else {
NSLog(@"Not an array");
}
在日志中我得到如下:
错误 操作无法完成。 (可可错误 3840。)
不是 数组
如果我删除错误处理并只留下一行
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data];
我的应用程序崩溃并显示以下消息:`
由于未捕获的异常而终止应用程序 'NSInvalidArgumentException',原因:'*** -[NSKeyedUnarchiver initForReadingWithData:]: 无法理解的存档 (0x3c, 0x3f, 0x78, 0x6d, 0x6c, 0x20, 0x76, 0x65)'
为什么会这样?什么是 Cocoa 错误 3840?
我的对象实现了 NSCoding 协议,并且有方法 encodeWithCoder 和 initWithCoder。我的对象的每个属性都必须编码/解码吗?
编辑:这是我的对象:
货币.h
@interface Currency : NSObject<NSCoding>{
CGFloat value;
NSString *code;
NSDate *date;
NSString *description;
NSString *imagePath;
}
@property (nonatomic, assign) CGFloat value;
@property (nonatomic, retain) NSString *code;
@property (nonatomic, retain) NSDate *date;
@property (nonatomic, retain) NSString *description;
@property (nonatomic, retain) NSString *imagePath;
货币.m
@implementation Currency
@synthesize value;
@synthesize code;
@synthesize date;
@synthesize description;
@synthesize imagePath;
static NSString * const keyCode = @"code";
static NSString * const keyDescription = @"description";
static NSString * const keyValue = @"value";
- (void)dealloc {
[code release];
[date release];
[description release];
[imagePath release];
[super dealloc];
}
- (void)encodeWithCoder:(NSCoder *)coder
{
if ([coder allowsKeyedCoding]) {
[coder encodeObject:code forKey: keyCode];
[coder encodeObject:description forKey: keyDescription];
[coder encodeFloat:value forKey: keyValue];
}
}
}
- (id)initWithCoder:(NSCoder *) coder {
self = [[Currency alloc] init];
if (self != nil)
{
code = [[coder decodeObjectForKey:keyCode] retain];
description = [[coder decodeObjectForKey:keyDescription] retain];
value = [coder decodeFloatForKey:keyValue];
}
return self;
}
@end
【问题讨论】:
-
数据定义是什么?发布 NSCoding 实现的实现。
标签: iphone objective-c ios