偏好存储相关

 
    // 1.获得沙盒根路径
    NSString *home = NSHomeDirectory();
    ///Users/WANG/Library/Developer/CoreSimulator/Devices/844F6A98-5241-4C8C-820A-3AB6535BEB69/data/Containers/Data/Application/D3C32B03-DBDB-4EDC-A722-7EF8CBBDE240

    // 2.document路径
    NSString *docPath = [home stringByAppendingPathComponent:@"Documents"];
    ///Users/WANG/Library/Developer/CoreSimulator/Devices/844F6A98-5241-4C8C-820A-3AB6535BEB69/data/Containers/Data/Application/D3C32B03-DBDB-4EDC-A722-7EF8CBBDE240/Documents

    // 3.拼接上文件后的跟径
    NSString *filepath = [docPath stringByAppendingPathComponent:@"data.plist"];
    ///Users/WANG/Library/Developer/CoreSimulator/Devices/844F6A98-5241-4C8C-820A-3AB6535BEB69/data/Containers/Data/Application/D3C32B03-DBDB-4EDC-A722-7EF8CBBDE240/Documents/data.plist

    // 1.利用NSUserDefaults,就能直接访问软件的偏好设置(Library/Preferences)
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    // 2.存储数据
    [defaults setObject:@"mj" forKey:@"account"];
    [defaults setInteger:10 forKey:@"age"];
    [defaults setBool:YES forKey:@"auto_login"];
    
    // 3.立刻同步
    [defaults synchronize];

    // 4.读取数据
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    NSString *account = [defaults objectForKey:@"account"];
    BOOL autoLogin = [defaults boolForKey:@"auto_login"];

    // 2.归档模型对象
    // 2.1.获得Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    // 2.3.将对象归档
    [NSKeyedArchiver archiveRootObject:stu toFile:path];


    // 1.获得Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:@"stu.data"];
    
    // 3.从文件中读取MJStudent对象
    MJStudent *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];


/** 该对象必须 声明协议
 *  将某个对象写入文件时会调用  
 *  在这个方法中说清楚哪些属性需要存储
 */
- (void)encodeWithCoder:(NSCoder *)aCoder
{
    [aCoder encodeObject:self.no forKey:@"no"];
    [aCoder encodeInt:self.age forKey:@"age"];
    [aCoder encodeDouble:self.height forKey:@"height"];
}

/**
 *  从文件中解析对象时会调用
 *  在这个方法中说清楚哪些属性需要存储
 */
- (id)initWithCoder:(NSCoder *)aDecoder 
{
    if (self = [super init]) {
        // 读取文件的内容
        self.no = [aDecoder decodeObjectForKey:@"no"];
        self.age = [aDecoder decodeIntForKey:@"age"];
        self.height = [aDecoder decodeDoubleForKey:@"height"];
    }
    return self;
}

posted on 2015-03-23 22:25  o无尘o  阅读(200)  评论(0编辑  收藏  举报