1

我正在尝试学习如何保存/加载图像,但我只是不明白为什么这不起作用。我将屏幕截图写入文件系统,如下所示:

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 子类的“init”方法中,我这样做:

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

数据文件路径方法:

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

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

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

    return pics.count;
}

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

4

1 回答 1

2

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

改变

[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]];
于 2013-10-02T14:20:31.017 回答