Objective-C学习之归档(Archiving),NSUserDefaults

新建一个OS X工程ArchiveDemo

一、归档(Archiving)

1command+N 新建类User,继承自NSObject

2、让User类实现NSCoding协议

3、添加变量(用户名,密码等)

//  User.h
#import <Foundation/Foundation.h>

@interface User : NSObject<NSCoding>

@property(nonatomic,copy)NSString *userName;
@property(nonatomic,copy)NSString *password;
@property(nonatomic,assign)NSInteger age;

@end

4、完成协议方法

//  User.m
#import "User.h"

@implementation User

@synthesize userName,password,age;

// 存储数据
-(void)encodeWithCoder:(NSCoder *)aCoder
{
    /** @brief 此处forKey的Key可自定义,只需在下面的init方法中读取时保持一致即可,与NSDictionary类似
     *  变量类型为Float或是其他类型时,选择对应的encode方法即可
     */
    [aCoder encodeObject:self.userName forKey:@"userName"];
    [aCoder encodeObject:self.password forKey:@"password"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}

// 读取数据
-(id)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super init]) {
        self.userName = [aDecoder decodeObjectForKey:@"userName"];
        self.password = [aDecoder decodeObjectForKey:@"password"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}

@end
5、在main.m中存储

NSArray *paths = [NSArray arrayWithObjects:NSHomeDirectory(), @"Documents", @"user.plist", nil];
        NSString *filePath = [NSString pathWithComponents:paths];
        // 初始化
        User *user = [[User alloc] init];
        user.userName = @"张三";
        user.password = @"123456";
        user.age = 12;
        // 归档
        BOOL Flag = [NSKeyedArchiver archiveRootObject:user toFile:filePath];
        if (Flag) {
            NSLog(@"保存成功");
        }
        else{
            NSLog(@"保存出错");
        }
6、读取数据

NSArray *paths = [NSArray arrayWithObjects:NSHomeDirectory(), @"Documents", @"user.plist", nil];
        NSString *filePath = [NSString pathWithComponents:paths];
        User *saved = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
        if(saved) {
            NSLog(@"\n userName = %@ \n password = %@\n age = %li",saved.userName,saved.password,saved.age);
        }

二、还有一种简便方法用来存储简单数据,NSUserDefaults

存储

// 对应类型使用对应方法即可   
 [[NSUserDefaults standardUserDefaults] setObject:@"李四" forKey:@"user"];
       
 [[NSUserDefaults standardUserDefaults] setInteger:22 forKey:@"age"];
       
 [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isMale"];
程序再次启动时读取值依然存在,用于iOS程序中保存个人信息及一些相关设置非常方便

NSString *user = [[NSUserDefaults standardUserDefaults] objectForKey:@"user"];
        
NSInteger age = [[NSUserDefaults standardUserDefaults] integerForKey:@"age"];
       
BOOL isMale = [[NSUserDefaults standardUserDefaults] boolForKey:@"isMale"];
               
NSLog(@"\n user = %@ \n age = %li \n isMale = %d",user,age,isMale);

你可能感兴趣的:(归档,NSUserDefaults,plist,存储数据,保存用户名密码)