我试图学习如何保存/加载图像,我只是不知道为什么这不会工作。我正在将截图写入文件系统,如下所示:
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]];
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子类,但它没有显示任何行。我究竟做错了什么?
答案 0 :(得分: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]];