一崩掘、基本概念
1七嫌、之前如果我們想要實現(xiàn)一個對象支持整個應用程序訪問,需要自己創(chuàng)建一個單例對象苞慢,而其實iOS系統(tǒng)內(nèi)部給我們提供了這個一個單例類诵原,NSUserDefaults,用來保存一些整個應用程序都能訪問到的數(shù)據(jù)
2、保存到NSUserDefaults對象的內(nèi)容都被放在沙盒Library/Oreferences文件夾中
3绍赛、對這個NSUserDefaults對象進行操作蔓纠,就相當于對文件進行操作
4、NSUserDefaults對象的存取方式和字典類似
二吗蚌、用法
1腿倚、通過單例方法找到NSUserDefault對象
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
2、用NSUserDefault對象存儲數(shù)據(jù)蚯妇,因為數(shù)據(jù)最終是存放在plist文件中敷燎,所以在這里可以存儲plist里面支持的數(shù)據(jù)類型,存取方式和字典類似
[defaults setInteger:12 forKey:@"age"];
3箩言、用NSUserDefault對象取數(shù)據(jù)
[defaults integerForKey:@"age"];
4硬贯、用NSUserDefault對象移除偏好設(shè)置里面的數(shù)據(jù)
[defaults removeObjectForKey:nil];
三、宏定義與NSUserDefault的搭配使用
1分扎、存值
#define kSaveMyDefault(A,B) [[NSUserDefaults standardUserDefaults] setObject:B forKey:A]
2澄成、取值
#define kFetchMyDefault(A) [[NSUserDefaults standardUserDefaults] objectForKey:A]
四、練習
1畏吓、應用第一次啟動有新手教程
1) 打開模擬本地緩存的工程
2)創(chuàng)建繼承與UIViewController的控制器FirstLaunchViewController墨状,用來做歡迎界面,.m文件如下
#import "FirstLaunchViewController.h"
#import "AppDelegate.h"
@interface FirstLaunchViewController ()
@end
@implementation FirstLaunchViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
UILabel *welcomeLabel = [[UILabel alloc]initWithFrame:self.view.frame];
welcomeLabel.text = @"歡迎您";
welcomeLabel.font = [UIFont boldSystemFontOfSize:20];
welcomeLabel.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:welcomeLabel];
}
- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event{
//獲取到應用程序的appDelegate
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
//在AppDelegate方法內(nèi)給重新設(shè)置window的主窗口
[appDelegate setWindowRootVC];
}
@end
3)AppDelegate.h? ??
? #import<UIKit/UIKit.h>
@interface AppDelegate : UIResponder
@property (strong, nonatomic) UIWindow *window;
//聲明一個用來切換window主窗口的window
- (void)setWindowRootVC;
@end
4) 修改AppDelegate.m的內(nèi)容如下
#import "AppDelegate.h"
#import "ViewController.h"
#import "FirstLaunchViewController.h"
//通過宏定義讓偏好設(shè)置存取值
#define kSaveMyDefault(A,B) [[NSUserDefaults standardUserDefaults] setObject:B forKey:A]
#define kFetchMyDefault(A) [[NSUserDefaults standardUserDefaults] objectForKey:A]
@interface AppDelegate ()
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
[self.window makeKeyAndVisible];
//設(shè)置window的根控制器
[self setWindowRootVC];
return YES;
}
- (void)setWindowRootVC{
//判斷之前是否啟動過
if (kFetchMyDefault(@"isFirst") == nil) {
//如果沒有啟動過就給鍵isFirst賦值
kSaveMyDefault(@"isFirst", @1);
FirstLaunchViewController *firstLaunchVC = [[FirstLaunchViewController alloc]init];
self.window.rootViewController = firstLaunchVC;
}else {
self.window.rootViewController = [[UINavigationController alloc]initWithRootViewController:[[ViewController alloc]init]];
}
}
@end