我以UIImagePicker
这样保存图片:
将图片保存在文件中,然后我将路径保存到NSUserDefaults
中的失败,然后在另一个类中,我通过此保存的路径检索图片。
代码:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
ideaImage.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
[picker dismissModalViewControllerAnimated:YES];
}
-(void)saveIdea_alt
{
[self performSelector: @selector(saveIdea) withObject:nil afterDelay:0.1];
}
-(void)saveIdea
{
UIImage *ideaPhoto = ideaImage.image;
NSData *imageData = UIImagePNGRepresentation(ideaPhoto);
NSString* imageName = @"MyImage.png";
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString* documentsDirectory = [paths objectAtIndex:0];
NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
[imageData writeToFile:fullPathToFile atomically:NO];
NSArray *arrayKeys = [[NSArray alloc]initWithObjects:@"ideaName",@"ideaCost",@"ideaNote", @"ideaImage", nil];
NSArray *arrayObjects = [[NSArray alloc]initWithObjects:ideaName.text,ideaCost.text,ideaNote.text,fullPathToFile , nil];
NSDictionary *dictionary = [[NSDictionary alloc]initWithObjects:arrayObjects forKeys:arrayKeys];
NSMutableArray *ideasArray = [[NSMutableArray alloc]initWithArray:[[NSUserDefaults standardUserDefaults]objectForKey:@"ideasArray"]];
[ideasArray addObject:dictionary];
[[NSUserDefaults standardUserDefaults]setObject:ideasArray forKey:@"ideasArray"];
[self dismissModalViewControllerAnimated:YES];
}
然而,之后我的应用程序变得缓慢,它会缓慢地保存和加载图像。我做错了什么? 谢谢!
答案 0 :(得分:2)
要看的一个有趣的优化是不将其保存到NSUserDefaults中,并使用Core Data。 这有很多原因,但一个重要的原因是,当您想要添加和删除NSUserDefaults中的内容时,应用程序必须将所有NSUserDefaults加载到内存中才能检索一个密钥。