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 - 添加延迟动画时,UIView 动画不起作用

objective-c - 如何在 Cocos2D 中的移动 Sprite 上添加文本?

iphone - iOS上如果一个view有好几层,drawRect是不是只能选择一个层显示?

iphone - 如何检查是否有 performSelector : waiting to be executed?

ios - TabBar 图像的大小应该是多少?

objective-c - Cocos2d v2 + 花栗鼠 : Fails when adding shapes to a CCLayer

ios - 在 iOS 7 上,如果最终包含在选项卡栏 Controller 中,则使用工具栏推送 Controller 会留下不可用空间的间隙

ios - NSMutableArray 中的 NSDictionary 在我的整个 for 循环中发生变化

iphone - 可以使用泰米尔语语言吗?

ios - 在 uitableviewcell 中更新标签文本而不重新加载整个表格