01 推出系統前的時間處理 --- 實現監聽和處理程式退出事件的功能

//檢視已經載入過時呼叫

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

//獲得應用程式的單例物件,該物件的核心作用是提供了程式執行期間的控制和協作工作。每個程式在執行期間,必須有且僅有該物件的一個例項

UIApplication *app = [UIApplication sharedApplication];

//通知中心時基礎框架的子系統。在本例中,它向所有監聽程式退出事件的物件,廣播訊息

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];

}

//建立一個方法,時程式在退出前,儲存使用者資料。

-(void)applicationWillResignActive:(id)sender {

//以遊戲應用為例,此外一般用來儲存場景、英雄狀態等資訊,也可以擷取當前遊戲介面,作為遊戲的下次啟動畫面

NSLog(@">>>>>>>>>>>>>>>>>>>>>saving data before exit");

}

**********************************************************************************************************************************************************************************************************************************

02 檢測App是否首次運用 --- NSUserDefaults的使用,它常被用於儲存程式的配置資料.

(當你關閉程式之後,再次開啟程式時,之前儲存的資料,依然可以從NSUserDefaults裡讀取.)

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

//獲得變數的布林值,當程式首次啟動時,由於從未設定過此變數,所以它的值時否

if (![[NSUserDefaults standardUserDefaults] boolForKey:@"everLaunched"]) {

//講變數賦值為真

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"everLaunched"];

[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunched"];

//使用同步方法,立即儲存修改

[[NSUserDefaults standardUserDefaults] synchronize];

}

else {

//如果不是第一次啟動程式,則設定變數的布林值為否

[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"firstLaunched"];

//使用同步方法,立即儲存修改

[[NSUserDefaults standardUserDefaults] synchronize];

}

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunched"]) {

//對於首次執行的程式,可以根據需求,進行各種初始工作。這裡使用一個簡單的彈出視窗.

UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"It's the first show." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];

[alerView show];

}

else {

UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"Hello Again" message:@"It's not the first show." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil, nil];

[alerView show];

}

}

**********************************************************************************************************************************************************************************************************************************

03 讀取和解析Plist屬性列表檔案

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"demoPlist" ofType:@"plist"];

NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile:plistPath];

//將字典轉換為字串物件

NSString *message = [data description];

//注意delegate的物件使用   ——wind(賈)

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Plist Content" message:message delegate:message cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

[alert show];

}

**********************************************************************************************************************************************************************************************************************************

04 通過程式碼建立Plist檔案 --- 通過編碼方式,建立屬性列表檔案

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

//初始化一個可變字典物件,作為屬性列表內容的容器.

NSMutableDictionary *data = [[NSMutableDictionary alloc] init];

//設定屬性列表檔案的內容

[data setObject:@"Bruce" forKey:@"Name"];

[data setObject:[NSNumber numberWithInt:40] forKey:@"Age"];

//獲得文件資料夾路徑

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *plistPath1 = [paths objectAtIndex:0];

//生成屬性列表檔案的實際路徑

NSString *filename = [plistPath1 stringByAppendingPathComponent:@"demoPlist.plist"];

//將可變字典物件,寫入屬性列表檔案.

[data writeToFile:filename atomically:YES];

//讀取並顯示屬性列表檔案

NSMutableDictionary *data2 = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];

NSString *message = [data2 description];

//使用資訊彈出視窗,顯示屬性列表檔案的所有內容

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Plist Content" message:message delegate:message cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

[alert show];

}

05 SQLite資料庫和表的建立 --- 資料庫表格的建立,和資料的插入 (Attentiong:Add A Framework( libsqpite3.tbd))

//////////////////////

ViewController.h檔案中:

//////////////////////

#import <UIKit/UIKit.h>

#import <sqlite3.h>  //資料框架標頭檔案

@interface ViewController : UIViewController

//建立一個數據庫物件的屬性

@property(assign,nonatomic)sqlite3 *database;

//開啟資料庫

-(void)openDB;

//用來建立資料庫表格

-(void)createTestList;

//用來往表格裡新增資料

-(void)insertTable;

ViewController.m檔案中:

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

//呼叫執行資料庫語句命令,用來執行非查詢的資料庫語句。最後在檢視載入完成後執行各方法.

//首先開啟或建立資料庫

[self openDB];

//然後建立資料庫中的表格

[self createTestList];

//再往表格裡新增相關資料。點選 執行,開啟模擬器預覽專案

[self insertTable];

}

//新建一個方法,用來存放資料庫檔案

-(NSString *)dataFilePath {

//獲得專案的文件目錄

NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *myDocPath = [myPaths objectAtIndex:0];

//建立一個字串,描述資料庫的存放路徑

NSString *filename = [myDocPath stringByAppendingPathComponent:@"data.db"];

NSLog(@"%@",filename);

return filename;

}

//建立一個方法,用來開啟資料庫

-(void)openDB {

//獲得資料庫路徑

NSString *path = [self dataFilePath];

//然後開啟資料庫,如果資料庫不存在,則建立資料庫.

sqlite3_open([path UTF8String], &_database);

}

//新增一個方法,用來建立資料庫中的表

-(void)createTestList {

//建立一條sql語句,用來在資料庫裡,建立一個表格.

const char *createSql = "create table if not exists people(ID INTEGER PRIMARY KEY AUTOINCREMENT,peopleId int,name test,age int)";

//第三個引數,是這條語句執行之後的回撥函式。第四個引數,是傳遞給回撥函式使用的引數。第五個引數是錯誤資訊

sqlite3_exec(_database, createSql, NULL, NULL, NULL);

}

//新增一個方法,用來往表格裡新增資料.

-(void)insertTable {

//建立一條sql語句,用來在資料庫表裡,新增一條記錄

const char *insertSql = "INSERT INTO testTable(peopleId,name,age) VALUES(1,'John',28)";

sqlite3_exec(_database, insertSql, NULL, NULL, NULL);

}

- (void)didReceiveMemoryWarning {

[super didReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

**********************************************************************************************************************************************************************************************************************************

06 SQLite資料庫的刪改查操作 --- 資料庫記錄的查詢,修改和刪除操作

//////////////////////

ViewController.h檔案中:

//////////////////////

#import <UIKit/UIKit.h>

#import <sqlite3.h>  //資料框架標頭檔案

@interface ViewController : UIViewController

//建立一個數據庫物件的屬性

@property(assign,nonatomic)sqlite3 *database;

//開啟資料庫

-(void)openDB;

//用來建立資料庫表格

-(void)createTestList;

//用來往表格裡新增資料

-(void)insertTable;

///////////////////////////

// 本節內容: 資料庫記錄的查詢,修改和刪除操作

//新增一個方法,用來查詢資料

-(void)queryTable;

//新增一個方法,用來刪除資料

-(void)deleteTable;

//新增一個方法,用來更新資料

-(void)updateTable;

//////////////////////

ViewController.m檔案中:

//////////////////////

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

/*

1.

//執行查詢方法,點選 執行

[self queryTable];

*/

/*

//1.

//    [self updateTable];

//2.

[self queryTable];

*/

/*

修改程式碼,演示資料庫記錄刪除功能

*/

//1.

//    [self deleteTable];

//2.

[self queryTable];

/////////////////////////////////////////////

}

//新建一個方法,用來存放資料庫檔案

-(NSString *)dataFilePath {

//獲得專案的文件目錄

NSArray *myPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *myDocPath = [myPaths objectAtIndex:0];

//建立一個字串,描述資料庫的存放路徑

NSString *filename = [myDocPath stringByAppendingPathComponent:@"data.db"];

NSLog(@"%@",filename);

return filename;

}

//建立一個方法,用來開啟資料庫

-(void)openDB {

//獲得資料庫路徑

NSString *path = [self dataFilePath];

//然後開啟資料庫,如果資料庫不存在,則建立資料庫.

sqlite3_open([path UTF8String], &_database);

}

//新增一個方法,用來建立資料庫中的表

-(void)createTestList {

//建立一條sql語句,用來在資料庫裡,建立一個表格.

const char *createSql = "create table if not exists people(ID INTEGER PRIMARY KEY AUTOINCREMENT,peopleId int,name test,age int)";

//第三個引數,是這條語句執行之後的回撥函式。第四個引數,是傳遞給回撥函式使用的引數。第五個引數是錯誤資訊

sqlite3_exec(_database, createSql, NULL, NULL, NULL);

}

//新增一個方法,用來往表格裡新增資料.

-(void)insertTable {

//建立一條sql語句,用來在資料庫表裡,新增一條記錄

const char *insertSql = "INSERT INTO testTable(peopleId,name,age) VALUES(1,'John',28)";

sqlite3_exec(_database, insertSql, NULL, NULL, NULL);

}

//////////////////////////////////////////

-(void)queryTable {

//首先開啟資料庫

[self openDB];

//建立一條語句,用來查詢資料庫記錄

const char *selectSql = "select peopelId, name from people";

//sqlite操作二進位制資料,需要用一個輔助的資料型別:sqlite3_stmt,這個資料型別,記錄了一個sql語句

sqlite3_stmt *statement;

//sqlite3_prepare_v2函式,用來完成sql語句的解析,第三個引數的含義是前面sql語句的長度,-1表示自動計算它的長度

if (sqlite3_prepare_v2(_database, selectSql, -1, &statement, nil) == SQLITE_OK) {

//當函式sqlite3_step返回值為SQLITE_ROW時,表明資料記錄集中,還包含剩餘資料,可以繼續進行便利操作

while (sqlite3_step(statement) == SQLITE_ROW) //SQLITE_OK SQLITE_ROW

{

//接受資料為整形的資料庫記錄

int _id = sqlite3_column_int(statement, 0);

//接受資料為字串型別的資料庫記錄

NSString *name = [[NSString alloc] initWithCString:(char *)sqlite3_column_text(statement, 1) encoding:NSUTF8StringEncoding];

//在控制檯輸出查詢到的資料

NSLog(@">>>>>>>>>>>>>>>>Id: %i, >>>>>>>>>>>>>>>>Name: %@",_id,name);

}

}

}

//建立一個方法,用來更新資料庫裡的資料

-(void)updateTable {

//首先開啟資料庫

[self openDB];

//用來建立一條語句,用來更新資料庫記錄

const char *sql = "update peoplt set name = 'Peter' WHERE people = 1";

sqlite3_exec(_database, sql, NULL, NULL, NULL);

//操作結束後,關閉資料庫

sqlite3_close(_database);

}

//建立一個方法,用來刪除資料庫裡的資料

-(void)deleteTable {

//首先開啟資料庫

[self openDB];

//建立一條語句,用來刪除資料庫記錄

const char *sql = "DELETE FROM people where peopleId = 1";

sqlite3_exec(_database, sql, NULL, NULL, NULL);

}

**********************************************************************************************************************************************************************************************************************************

07 NSKeyedArchiver儲存和解析資料

(1) 建立以Car類;

//////////////////////

Car.h檔案中:

//////////////////////

#import <Foundation/Foundation.h>

//新增NSCoding 協議,用來支援資料類和資料流間的編碼和解碼。通過繼承NSCopying協議,使資料物件支援拷貝.

@interface Car : NSObject<NSCoding,NSCopying>

//給當前類新增2個屬性

@property (nonatomic,retain)NSString *brand;

@property (nonatomic,retain)NSString *color;

@end

//////////////////////

Car.m檔案中:

//////////////////////

#import "Car.h"

@implementation Car

//然後,新增一個協議方法,用來對模型物件進行序列化操作.

-(void)encodeWithCoder:(NSCoder *)aCoder {

//對2個屬性進行編碼操作

[aCoder encodeObject:_brand forKey:@"_brand"];

[aCoder encodeObject:_color forKey:@"_color"];

}

//接著新增另一個來自協議的方法,用來對模型物件進行反序列化操作

-(id)initWithCoder:(NSCoder *)aDecoder {

if (self != [super init]) {

_brand = [aDecoder decodeObjectForKey:@"_brand"];

_color = [aDecoder decodeObjectForKey:@"_color"];

}

return self;

}

//實現NSCoping協議的copyWithZone方法,用來響應拷貝訊息

-(id)copyWithZone:(NSZone *)zone {

Car *car = [[[self class] allocWithZone:zone] init];

car.brand = [self.brand copyWithZone:zone];

car.color = [self.color copyWithZone:zone];

return car;

}

///////////////////////////

ViewController.m檔案中:

///////////////////////////

#import "ViewController.h"

#import "Car.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

CGRect rect = CGRectMake(80, 100, 150, 30);

//建立一個按鈕,點選按鈕會新建一個Car物件,並把該物件歸檔

UIButton *initData = [[UIButton alloc] initWithFrame:rect];

//設定按鈕的背景顏色為紫色

[initData setBackgroundColor:[UIColor purpleColor]];

//設定按鈕標題文字

[initData setTitle:@"Initialize data" forState:UIControlStateNormal];

//設定按鈕繫結事件

[initData addTarget:self action:@selector(initData) forControlEvents:UIControlEventTouchUpInside];

CGRect rect2 = CGRectMake(80, 200, 150, 30);

//接著建立另一個按鈕,點選按鈕會解析已歸檔的物件

UIButton *loadData = [[UIButton alloc] initWithFrame:rect2];

[loadData setBackgroundColor:[UIColor purpleColor]];

[loadData setTitle:@"Load data" forState:UIControlStateNormal];

[loadData addTarget:self action:@selector(loadData) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:initData];

[self.view addSubview:loadData];

}

//新建一個方法,用來設定歸檔物件的儲存路徑

-(NSString *)fileDirectory {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

return [documentsDirectory stringByAppendingPathComponent:@"archiveFile"];

}

//建立一個方法,用來初始化物件,並將物件歸檔

-(void)initData {

Car *car = [[Car alloc] init];

car.brand = @"Apple";

car.color = @"White";

NSMutableData *data = [[NSMutableData alloc] init];

//初始化一個歸檔物件,用來處理物件的歸檔

NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];

[archiver encodeObject:car forKey:@"dataKey"];

//完成歸檔物件的編碼操作

[archiver finishEncoding];

//將歸檔後的資料,儲存到磁碟上

[data writeToFile:[self fileDirectory] atomically:YES];

//建立一個視窗,用來提示歸檔成功

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Information" message:@"Success to initialize data." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

[alert show];

}

//建立一個方法,用來解析物件

-(void)loadData {

NSString *filePath = [self fileDirectory];

if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:filePath];

NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];

Car *car = [unarchiver decodeObjectForKey:@"dataKey"];

//完成解碼操作

[unarchiver finishDecoding];

NSString *info = [NSString stringWithFormat:@"Car Brand:%@\nCar Color:%@",car.brand,car.color];

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Information" message:info delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

[alert show];

}

}

**********************************************************************************************************************************************************************************************************************************

08 使用MD5加密資料 --- 系統自帶的md5加密功能(Attention:Add a framework(libcommonCrypto.tbd))

ViewController.m檔案中:

#import "ViewController.h"

#import <CommonCrypto/CommonCrypto.h>  //加密功能標頭檔案

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {

[super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

//定義一個字串物件

NSString *str = @"Hello Apple";

//將字串物件轉換成C語言字串

const char *representation = [str UTF8String];

//建立一個標準長度的字串

unsigned char md5[CC_MD5_DIGEST_LENGTH];

//對C語言字串進行加密,並將結果存入變數

CC_MD5(representation, strlen(representation), md5);

//建立一個可變的字串變數

NSMutableString *mutableStr = [NSMutableString string];

for (int i = 0; i < 16; i ++) {

//通過遍歷該變數,將加密後的結果,存入可變字串變數.

[mutableStr appendFormat:@"%02X",md5[i]];

}

//使用警告視窗物件,顯示加密後的結果.

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"MD5" message:mutableStr delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

[alert show];

}