iOS開發學習專題-基礎知識(五) NSDate時間 NSUserDefaults本地存儲 NSNotification系統通知的詳細使用方式

本文主要講解的是 NSDate時間NSUserDefaults本地存儲NSNotification系統通知的詳細使用方式,也是NS系列基礎知識的最後一篇文章

文章是博主原創,轉載請標明出處http://blog.csdn.net/werctzzz/article/details/72677981

NSUserDefaults是iOS系統提供的一個單例類(iOS提供了若干個單例類),通過類方法standardUserDefaults可以獲取NSUserDefaults單例。
NSUserDefaults適合存儲輕量級的本地數據。存儲的數據在關閉程序之後,再次運行的時候依然存在,它的數據存儲在/Library/Prefereces沙盒路徑下.

// NSUserDefaults支持數據格式:
//    NSNumber
//    NSString
//    NSArray
//    NSDictionary
//    BOOL
//    NSDate
// NSUserDefaults提供的快捷對象存儲方式:
//    setBool:  forKey:
//    setFloat: forKey:
//    setInteger:   forKey:
//    setDouble:    forKey:
//    setURL:   forKey:
    
    // 1.初始化:
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    // 2.NSUserDefaults操作,和字典一樣通過key值來存入和讀取數據
    // 2.1 創建存入的數據
    [defaults setInteger:23 forKey:@"myInteger"];
    // 2.2 數據存入磁盤
    [defaults synchronize];
    // ⭐️方法synchronise是爲了強制存儲,其實並非必要,因爲這個方法會在系統中默認調用,但是你確認需要馬上就存儲,這樣做是可行的。
    
    // 2.3 通過key值讀取數據
    NSLog(@"%ld",[defaults integerForKey:@"myInteger"]);
    
    // 3.因爲NSUserDefaults所存儲的對象和值是不可變的(只能覆蓋)
    // 3.1 所以在存可變的類型時候我們需要這樣
    NSMutableArray *mutableArray1 = [NSMutableArray arrayWithObjects:@"123",@"234", nil];
    NSArray * array = [NSArray arrayWithArray:mutableArray1];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    [user setObject:array forKey:@"Array"];
    // 3.2 在讀取的時候我們也是需要這樣來操作
    NSMutableArray *mutableArray2 = [NSMutableArray arrayWithArray:[user objectForKey:@"記住存放的一定是不可變的"]];
    
    // 4.我們可以試試存儲圖片(上期講過的NSData)
    UIImage *image1 =[UIImage imageNamed:@"aaimg"];
    NSData *imageData1 = UIImageJPEGRepresentation(image1, 100);//把image歸檔爲NSData
    [user setObject:imageData1 forKey:@"image"];
    // 讀取
    NSData *imageData2 = [user dataForKey:@"image"];
    UIImage *image2 = [UIImage imageWithData:imageData2];

引用“iOS 提供了一種 "同步的" 消息通知機制,觀察者只要向消息中心註冊, 即可接受其他對象發送來的消息,消息發送者和消息接受者兩者可以互相一無所知,完全解耦。這種消息通知機制可以應用於任意時間和任何對象,觀察者可以有多個,所以消息具有廣播的性質,只是需要注意的是,觀察者向消息中心註冊以後,在不需要接受消息時需要向消息中心註銷,這種消息廣播機制是典型的“Observer”模式。這個要求其實也很容易實現. 每個運行中的application都有一個NSNotificationCenter的成員變量,它的功能就類似公共欄. 對象註冊關注某個確定的notification(如果有人撿到一隻小狗,就去告訴我). 我們把這些註冊對象叫做 observer. 其它的一些對象會給center發送notifications(我撿到了一隻小狗). center將該notifications轉發給所有註冊對該notification感興趣的對象. 我們把這些發送notification的對象叫做 poster。消息機制常常用於在向服務器端請求數據或者提交數據的場景,在和服務器端成功交互後,需要處理服務器端返回的數據,或發送響應消息等,就需要用到消息機制。”

- (void)NSNotificationUseFunction{
    // 通知模式NSNotification(也稱消息中心)
    
    // 1.註冊接收的通知者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(test:) name:@"testNotification" object:nil];
    // 1.1發送通知
    [self sendUsername];
    
    // 系統通知
    // 2.APP切換到後臺
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterBack:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    
    // 3.APP切換回前臺
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterFace:) name:UIApplicationWillEnterForegroundNotification  object:nil];
}

// 1.1通知發送者
- (void)sendUsername{
    // 創建要發送的數據
    NSDictionary * data = [NSDictionary dictionaryWithObject:@"我是名字" forKey:@"username"];
    // 向中心發送數據
    [[NSNotificationCenter defaultCenter]postNotificationName:@"testNotification" object:nil userInfo:data];
}
// 1.2接收通知的內容
- (void)test:(NSNotification*)testNotifi{
    NSDictionary * data = [testNotifi userInfo];
    NSString * userName = [data objectForKey:@"username"];
    NSLog(@"username:%@",userName);
}
// 2.App切換到後臺
- (void)enterBack:(NSNotification*)enterBackNotifi{
    NSLog(@"進入到後臺");
}
// 3.App切換到前臺
- (void)enterFace:(NSNotification*)enterFaceNotifi{
    NSLog(@"進入到前臺");
}

NSDate 是蘋果提供的一個類,在iOS開發中用於處理時間和日期

// 獲取當前日期
    // 1.初始化
    NSDate *date = [NSDate date];
    NSLog(@"當前時間 date = %@",date);
    // 2.改變時間
    // 獲取從某個日期開始往前或者往後多久的日期,此處60代表60秒,如果需要獲取之前的,將60改爲-60即可
    date = [[NSDate alloc] initWithTimeInterval:60 sinceDate:[NSDate date]];
    NSLog(@"當前時間 往後60s的時間date = %@",date);// 可以和上面的打印時間做比較
    
    // 3.當地時間的獲取,
    // 應爲iOS默認是格林尼治時間,所以需要用NSTimeZone矯正時間時區,NSTimeZone會獲取本機定位的區域用來獲取時區
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localDate = [date  dateByAddingTimeInterval: interval];
    NSLog(@"當前地區時間 localDate = %@",localDate);
    
    // 4.時間的格式化
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
    NSLog(@"當前時間 = %@ ,年 = %ld ,月=%ld, 日=%ld",date,currentYear,currentMonth,currentDay);
    
    // 5.NSDate與NSString
    NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
    // 5.1設置日期格式
    [dateFormatter setDateFormat:@"年月日 YYYY/mm/dd 時間 hh:mm:ss"];
    NSString *dateString = [dateFormatter stringFromDate:date];
    NSLog(@"dateString = %@",dateString);
    // 5.2設置日期格式
    [dateFormatter setDateFormat:@"YYYY-MM-dd"];
    NSString *year = [dateFormatter stringFromDate:date];
    NSLog(@"年月日 year = %@",year);
    // 5.3設置時間格式
    [dateFormatter setDateFormat:@"hh:mm:ss"];
    NSString *time = [dateFormatter stringFromDate:date];
    NSLog(@"時間 time = %@",time);
    // 可以看看打印結果是什麼~
    
    // 6.日期的比較NSDate的比較
    // 當前時間
    NSDate *currentDate = [NSDate date];
    // 比當前時間晚一個小時的時間
    NSDate *laterDate = [[NSDate alloc] initWithTimeInterval:60*60 sinceDate:[NSDate date]];
    // 比當前時間早一個小時的時間
    NSDate *earlierDate = [[NSDate alloc] initWithTimeInterval:-60*60 sinceDate:[NSDate date]];
    // 比較哪個時間遲
    if ([currentDate laterDate:laterDate]) {
        NSLog(@"current-%@比later-%@晚",currentDate,laterDate);
    }
    // 比較哪個時間早
    if ([currentDate earlierDate:earlierDate]) {
        NSLog(@"current-%@ 比 earlier-%@ 早",currentDate,earlierDate);
    }
    if ([currentDate compare:earlierDate]==NSOrderedDescending) {
        NSLog(@"current 晚");
    }
    if ([currentDate compare:currentDate]==NSOrderedSame) {
        NSLog(@"時間相等");
    }
    if ([currentDate compare:laterDate]==NSOrderedAscending) {
        NSLog(@"current 早");
    }
總算在百忙之中把NS常用類的基礎知識整理完了,如果有什麼寫不對,寫不全的地方,歡迎大家來留言反饋。作爲知識共享,首先要自己能明白,自己能有自己的想法,然後再給大家展現自己的想法,希望能拋磚引玉~之後會開始整理UI部分以及各種小知識點~敬請期待

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章