UI进阶__保存数据

方法一:保存在偏好设置中

// 将数据保存到偏好设置中,不需要关心路径在哪里,不要保存大数据,比如图片。
    // 偏好设置对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"jack" forKey:@"name"];
    [defaults setObject:@"rose" forKey:@"password"];
    [defaults setInteger:100 forKey:@"age"];
    [defaults setDouble:1.9 forKey:@"height"];
    [defaults setBool:YES forKey:@"sex"];
    [defaults setFloat:189.9 forKey:@"weight"];

    // 在ios8之前还有加入下面代码
    // 立即同步,立即保存数据
    [defaults synchronize];
/** * 读取 */
- (void)loadUserInfo {
    // 获得偏好设置对象
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    self.accountField.text = [defaults objectForKey:HMAccount];
    self.rmbSwitch.on = [defaults boolForKey:HMRmbSwitch];
    self.autoLoginSwitch.on = [defaults boolForKey:HMAutoLoginSwitch];

方法二:
// 保存联系人信息到沙盒中

    // 获得doc文件夹路径
// NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
// NSString *filePath = [doc stringByAppendingPathComponent:@"contacts.data"];
    [NSKeyedArchiver archiveRootObject:self.contacts toFile:HMContactFilePath];
 // 从沙盒中获得联系人数据
        _contacts = [NSKeyedUnarchiver unarchiveObjectWithFile:HMContactFilePath];

注:需要遵守<NSCoding>协议,实现两个方法
- (void)encodeWithCoder:(NSCoder *)encoder {
    [encoder encodeObject:self.name forKey:@"name"];
    [encoder encodeObject:self.phone forKey:@"phone"];
}

- (instancetype)initWithCoder:(NSCoder *)decoder {
    if (self = [super init]) {
        self.name = [decoder decodeObjectForKey:@"name"];
        self.phone = [decoder decodeObjectForKey:@"phone"];
    }
    return self;
}

你可能感兴趣的:(UI进阶__保存数据)