iphone - iOS 将 View 和图像编码/解码到文件目录中

标签 iphone objective-c ios ipad

我有一个对象,它有一个自定义 UIView 的 NSMutableArray、一个 UIImage 和几个字符串。

我将那个对象放入字典中。字典被插入 NSData 然后我这样做:

NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
path = [paths objectAtIndex:0];

NSString *fileName = DATA;
path = [path stringByAppendingPathComponent:fileName];

NSMutableData *data = [[NSMutableData alloc]init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
[archiver encodeObject:dict forKey: DATA];
[archiver finishEncoding];

[[NSFileManager defaultManager] createFileAtPath:path
                                        contents:data
                                      attributes:nil];

保存成功。当我尝试加载数据时,文件系统显示我的对象已保存,但当我尝试解码时,它说我的数据为 NULL。

这是我的解码代码:

-(NSDictionary*)loadData
{
NSString *path;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,    NSUserDomainMask, YES);
path = [paths objectAtIndex:0];
NSArray *directoryContent = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:NULL];

if (directoryContent != nil && [directoryContent count] > 0)
{
    NSLog(@"CONTENT COUNT: %d",[directoryContent count]);
    NSString *fileName = DATA;
    path = [path stringByAppendingPathComponent:fileName];
    NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[directoryContent objectAtIndex:0]];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
    NSDictionary *dict = [unarchiver decodeObjectForKey: DATA];
    [unarchiver finishDecoding];

    return dict;
}
else
    return nil;
}

我的应用程序允许用户移动一堆 View ,我只是想找到一种简单的方法来存储 View 帧和转换,而不必提取每个 int/string 值。我也希望不必将 UIImage 分解为字节数组,然后将其重新加载回 UIImage。

我是不是在做一些疯狂的事情,希望获得不可能实现的功能?

我唯一的选择是将数组中的每个 UIView 分解为用于变换、框架等的单独值吗?

想法?

最佳答案

文档目录是否包含除您的数据文件之外的任何内容? (我相信它总是至少包含一个名为“收件箱”的子目录。)我在您的 loadData 方法中注意到了这些行:

    path = [path stringByAppendingPathComponent:fileName];
    NSData *data = [[NSMutableData alloc]initWithContentsOfFile:[directoryContent objectAtIndex:0]];

您将 fileName 附加到 path,但是您没有使用它。您刚刚读取了 directoryContent 中提到的第一个文件。

关于iphone - iOS 将 View 和图像编码/解码到文件目录中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8025676/

相关文章:

ios - 单击按钮在 ios 中打开拨号程序

ios - 释放后访问实例变量

ios - 从 XCode 下载共享 App Group Container

iphone - @autoreleasepool 做什么?

iphone - 如何为 NSPredicate 连接两个字符串,即名字和姓氏

ios - SKLabelNode labelNodeWithFontNamed:

ios - 如何将两个数组对象作为对象和键添加到 Objective C 中的第三个数组

ios - UITextfield 对覆盖文本属性的错误访问

iphone - 具有透明背景的 UIControl

ios - 向分组的 UITableView 添加阴影