问题描述
我有这个对象。
@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
我想保存一个数组将此对象填充到磁盘上的文件中。
I want to save an array filled with this objects to a file on disk.
我这样做:
写
[NSKeyedArchiver archiveRootObject:arr toFile:file];
阅读
NSArray *entries = [NSKeyedUnarchiver unarchiveObjectWithFile:name];
return entries;
但是readed数组总是空的,我不知道为什么,我有一些问题。
But the readed array is always empty, i dont know why, i have some questions.
我应该使用什么格式的文件路径? on toFile:?
What format should i use for file path? on toFile:?
对象上的NSArray用NSData对象填充,所以我可以对它们进行编码吗?
The NSArray on the object is filled with NSData objects, so i can encode them?
我真的迷失了。
推荐答案
看看NSKeyedArchiver的文档,特别是 method。
Take a look at the documentation of NSKeyedArchiver, especially the archiveWithRootObject:toFile: method.
路径基本上是应该存储文件的位置,包括文件名。例如,您可以将数组存储在应用程序Documents文件夹中,文件名称为 Storage 。下面的代码片段很常见:
The path is basically where the file should be stored including the file name. For example you can store your array in your app Documents folder with file name called Storage. The code snippet below is quite common:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex: 0];
NSString* docFile = [docDir stringByAppendingPathComponent: @"Storage"];
使用方法 NSSearchPathForDirectoriesInDomains 而不是绝对路径,因为Apple可能正在改变文档文件夹路径是他们想要的。
The method NSSearchPathForDirectoriesInDomains is used instead of absolute path because Apple can be changing the Documents folder path as they want it.
您可以使用上面的docFile字符串提供给archiveWithRootObject:toFile:方法的toFile参数。
You can use the docFile string above to be supplied to the toFile parameter of the archiveWithRootObject:toFile: method.
这篇关于编写和读取自定义对象到文件IOS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!