iOS-数据存储方式二之偏好设置存储(NSUserDefaults)

  • 用来保存应用程序设置和属性,用户保存的数据,用户再次打开应用程序或者开机后这些数据仍然存在。每个应用都有个NSUserDefaults实例,通过它来存取偏好设置,比如,保存用户名、字体大小、是否自动登录。
  • NSUserDefaults可以存储的数据类型包括:NSData、NSString、NSNumber、NSDate、NSArray、NSDictionary。如果要存储其他类型,则需要转换为前面的类型,才能用NSUserDefaults存储。
  • NSUserDefaults存储的东西,会保存到沙盒的Library–>Preferences路径下。
  • NSUserDefaults存储的东西,实际上就是存储在plist文件中。

NSUserDefaults存储数据:

 NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud setObject:@"yes" forKey:@"nightSwitch"];
            //立即存储
            [ud synchronize];

NSUserDefaults读取数据:

NSString *value = [[NSUserDefaults standardUserDefaults] objectForKey:@"nightSwitch"];

NSUserDefaults删除数据:

            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud removeObjectForKey:@"nightSwitch"];
            [ud synchronize];

**下面,用NSUserDefaults做一些练习:
一、
app第一次运行时候,第一组第一行存储当前时间(具体到时,分)再加两分钟。每次启动app时候,判断启动app时候的时间是否超过存储的时间,如果超过就弹出提示框:会员时间到期。
二、
夜间模式是否开启,如果开启,下次启动app时候也开启着该UISwitch。**

代码如下:

//
//  ViewController.h
//  Archiver
//
//  Created by HZhenF on 2017/5/30.
//  Copyright © 2017年 Huangzhengfeng. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController


@end

//
//  ViewController.m
//  Archiver
//
//  Created by HZhenF on 2017/5/30.
//  Copyright © 2017年 Huangzhengfeng. All rights reserved.
//

#import "ViewController.h"
#import "MyCell.h"

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong) UITableView *tableView;

@property(nonatomic,strong) NSString *valueString;

@property(nonatomic,strong) NSString *valueDate;

@end

@implementation ViewController

-(UITableView *)tableView
{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStyleGrouped];
        [_tableView registerClass:[MyCell class] forCellReuseIdentifier:@"myCell"];
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    NSString *value = [[NSUserDefaults standardUserDefaults] objectForKey:@"nightSwitch"];
    self.valueString = value;

    NSString *value1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"deadline"];
    self.valueDate = value1;

//    NSLog(@"%@",NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0]);

}

-(BOOL)prefersStatusBarHidden
{
    return YES;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 3;
    }
    else if (section == 1)
    {
        return 6;
    }
    return 2;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];
    if (!cell) {
        cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"myCell"];
    }
    cell.nightSwitch.hidden = YES;
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            cell.leftName.text = @"会员到期时间";
            cell.rightDesc.text = self.valueDate;


            NSString *valueStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"deadline"];

            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyy-MM-dd HH:mm";
            NSDate *VipDate = [formatter dateFromString:valueStr];

            if ([VipDate timeIntervalSinceDate:[NSDate date]] <= 0) {
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的会员日期到期了!" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                }];
                [alertVC addAction:okAction];
                [self presentViewController:alertVC animated:YES completion:nil];
            }

        }
        else if(indexPath.row == 1)
        {
            cell.leftName.text = @"商城";
        }
        else
        {
            cell.leftName.text = @"在线听歌免流量";
        }
    }
    else if (indexPath.section == 1)
    {
        if (indexPath.row == 0) {
            cell.leftName.text = @"设置";
        }
        else if(indexPath.row == 1)
        {
            cell.leftName.text = @"夜间模式";
            cell.nightSwitch.hidden = NO;
            if ([self.valueString isEqualToString:@"yes"]) {
                [cell.nightSwitch setOn:YES];
            }
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else
        {
            cell.leftName.text = @"xxxxx";
        }
    }



    return cell;
}


@end
//
//  MyCell.h
//  Archiver
//
//  Created by HZhenF on 2017/5/30.
//  Copyright © 2017年 Huangzhengfeng. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MyCell : UITableViewCell

@property(nonatomic,strong) UILabel *leftName;

@property(nonatomic,strong) UILabel *rightDesc;

@property(nonatomic,strong) UISwitch *nightSwitch;

@end
//
//  MyCell.m
//  Archiver
//
//  Created by HZhenF on 2017/5/30.
//  Copyright © 2017年 Huangzhengfeng. All rights reserved.
//

#import "MyCell.h"

#define ScreenW [UIScreen mainScreen].bounds.size.width
#define ScreenH [UIScreen mainScreen].bounds.size.height
#define ratioW ScreenW/414
#define rationH ScreenH/736

@implementation MyCell

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.leftName = [[UILabel alloc] init];
        self.rightDesc = [[UILabel alloc] init];
        self.rightDesc.font = [UIFont systemFontOfSize:12.0];
        self.rightDesc.textAlignment = NSTextAlignmentCenter;
        self.nightSwitch = [[UISwitch alloc] init];
        [self.nightSwitch addTarget:self action:@selector(nightSwitchAction:) forControlEvents:UIControlEventTouchUpInside];

        [self addSubview:self.leftName];
        [self addSubview:self.rightDesc];
        [self addSubview:self.nightSwitch];
    }
    return self;
}

-(void)layoutSubviews
{
    [super layoutSubviews];
    CGRect frame = self.frame;
    self.leftName.frame =  CGRectMake(10, (frame.size.height - 30*rationH)*0.5,150*ratioW , 30*rationH);
    self.rightDesc.frame = CGRectMake(ScreenW - 150*rationH - 10, (frame.size.height - 30*rationH)*0.5, 150*ratioW , 30*rationH);
    self.nightSwitch.frame = CGRectMake(ScreenW - 70*ratioW,  (frame.size.height - 30*rationH)*0.5, 70*ratioW , 30*rationH);

    //判断截止日期
    [self judgeDeadLine];
}

-(void)judgeDeadLine
{
   NSString *valueStr = [[NSUserDefaults standardUserDefaults] objectForKey:@"deadline"];

    if (!valueStr) {
        NSDate *VipDate = [NSDate date];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyy-MM-dd HH:mm";
        NSString *dateString = [formatter stringFromDate:[VipDate dateByAddingTimeInterval:120]];
        NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
        [ud setObject:dateString forKey:@"deadline"];
        [ud synchronize];
    }
    else
    {
        //不做任何操作
    }

}

-(void)nightSwitchAction:(UISwitch *)sender
{
     NSString *value = [[NSUserDefaults standardUserDefaults] objectForKey:@"nightSwitch"];
    //为空的时候才存
    if (!value) {
        if (sender.on) {
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud setObject:@"yes" forKey:@"nightSwitch"];
            [ud synchronize];
        }
        else
        {
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud removeObjectForKey:@"nightSwitch"];
            [ud synchronize];
        }
    }
    //value已经有值了
    else
    {
        if (!sender.isOn) {
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            [ud removeObjectForKey:@"nightSwitch"];
            [ud synchronize];
        }
    }
}

@end

程序第一次启动:

这里写图片描述


打开夜间模式后,程序再次启动:

这里写图片描述


查看生成的plist文件内容:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值