标签:
#import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (strong, nonatomic) UIWindow *window; @end
#import "AppDelegate.h" #import "RootViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; self.window.rootViewController = [[RootViewController alloc] init]; [self.window makeKeyAndVisible]; return YES; } @end
#import <UIKit/UIKit.h> @interface RootViewController : UIViewController @end
#import "RootViewController.h" #import "User.h" @interface RootViewController () @end @implementation RootViewController - (void)viewDidLoad { [super viewDidLoad]; User *user = [User userInfo]; user.name = @"LF"; user.address = @"广州"; NSLog(@"归档前===%@===%@",user.name,user.address); //归档 [NSKeyedArchiver archiveRootObject:user toFile:[self fileToPath]]; //解归档 User *user2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self fileToPath]]; NSLog(@"归档后===%@===%@",user2.name,user2.address); user2.address = @"北京"; [NSKeyedArchiver archiveRootObject:user2 toFile:[self fileToPath]]; //解归档 User *user3 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self fileToPath]]; NSLog(@"重新归档后===%@===%@",user3.name,user3.address); } /** * 获取文件路径 */ - (NSString *)fileToPath{ NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *path = [docPath stringByAppendingString:@"userInfomation"]; NSLog(@"%@",path); return path; } @end
#import <Foundation/Foundation.h> @interface User : NSObject<NSCoding> @property(nonatomic, copy) NSString *name; @property(nonatomic, copy) NSString *address; + (User*)userInfo; @end
#import "User.h" #define userName @"name" #define userAddress @"address" @implementation User #pragma mark 单例模式 static User *instance = nil; + (User*)userInfo{ static dispatch_once_t predicate; dispatch_once(&predicate, ^{ instance = [[self alloc] init]; }); return instance; } //归档 - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:_name forKey:userName]; [aCoder encodeObject:_address forKey:userAddress]; } // 解归档 #pragma mark NSCoding协议方法 - (instancetype)initWithCoder:(NSCoder *)aDecoder{ self = [super init]; if (self) { self.name = [aDecoder decodeObjectForKey:userName]; self.address = [aDecoder decodeObjectForKey:userAddress]; } return self; } @end
标签:
原文地址:http://www.cnblogs.com/lantu1989/p/5226452.html