用archive儲存圖片到本地,
原始碼:http://url.cn/OaPZa2
今天用到了將archive圖片儲存到本地。
儲存圖片是不能用NSUserDefault來儲存的,NSUserDefault只能儲存基礎的類型,並不能儲存對象。
:
代碼:
- (void)viewDidLoad{ [super viewDidLoad]; // Do any additional setup after loading the view. //初始化背景圖 imageView=[[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)]; imageView.backgroundColor=[UIColor redColor]; [self.view addSubview:imageView]; //將圖片儲存 [self archive]; //提取儲存在本地的圖片 [self unarchive]; }#pragma -mark -functions//歸檔-(void)archive{ NSData *data=[NSKeyedArchiver archivedDataWithRootObject:[UIImage imageNamed:@"1.jpg"]]; NSUserDefaults *imageDefault = [NSUserDefaults standardUserDefaults]; [imageDefault setObject:data forKey:@"image"]; [imageDefault synchronize];}//反歸檔-(void)unarchive{ NSData* data = [[NSUserDefaults standardUserDefaults]objectForKey:@"image"]; id image= [NSKeyedUnarchiver unarchiveObjectWithData:data]; imageView.image=image; }