ios - 写入/加载到/从文件

标签 ios objective-c uitableview

我正在尝试学习如何保存/加载图像,但我只是不明白为什么这行不通。我正在像这样向文件系统写入屏幕截图:

if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)])
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, NO, [UIScreen mainScreen].scale);
else
    UIGraphicsBeginImageContext(self.view.bounds.size);

[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData * data = UIImagePNGRepresentation(image);

NSArray *directories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [directories objectAtIndex:0];
NSString *key = [documentsDirectory stringByAppendingPathComponent:@"screenshots.archive"];

[data writeToFile:key atomically:YES];

在我的 UITableView 子类的“初始化”方法中,我这样做:

pics = [[NSMutableDictionary alloc]initWithContentsOfFile:[self dataFilePath]];

数据文件路径方法:

- (NSString *)dataFilePath
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:@"screenshots.archive"];
}

为了测试这是否有效,我有这个委托(delegate)方法:

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return pics.count;
}

我通过截图来测试它,然后初始化我的 UITableview 子类,但它没有显示任何行。我究竟做错了什么?

最佳答案

代码有几个关键问题导致它无法运行。您将图像数据直接存储到文件中,并尝试将其作为字典读回。您需要先将图像包装在一个数组中,然后将该数组写入文件。然后您需要将该文件读入一个数组以供表格显示。总结变化:

改变

[data writeToFile:key atomically:YES];

NSMutableArray *storageArray = [NSMutableArray arrayWithContentsOfFile:key];

if(!storageArray)
    storageArray = [NSMutableArray arrayWithObject:data];
else
    [storageArray addObject:data];

[storageArray writeToFile:key atomically:YES];

和改变

pics = [[NSMutableDictionary alloc]initWithContentsOfFile:[self dataFilePath]];

pics = [[NSArray alloc] initWithContentsOfFile:[self dataFilePath]];

关于ios - 写入/加载到/从文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19138511/

相关文章:

objective-c - 从 Info plist 获取数据

android - 我应该如何定位适用于 Android 和 iOS 的基于 Web 的管理工具?

iphone - ios4 中不显示外部视频

ios - 如何编辑使用 dequeueReusableCellWithIdentifier 后在新单元格中自动创建的文本标签

iphone - 如何使用 swift 更改 UICell 上字母和线条之间的间距

iOS 网络连接失败策略建议

iphone - iOS - 如何在两个 View 之间创建自定义过渡?

ios - 重新加载 ViewController

c++ - OSX CGGetActiveDisplayList -> ld : symbol(s) not found for architecture x86_64

ios - 如何在 UIKeyboard 可见时更改 UITableView 大小?