【代碼筆記】iOS-archive儲存圖片到本地,
一,工程圖:
二,代碼:
RootViewController.h
#import <UIKit/UIKit.h>@interface RootViewController : UIViewController{ UIImageView *imageView;}@end
RootViewController.m
#import "RootViewController.h"@interface RootViewController ()@end@implementation RootViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{ self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self;}- (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; }