iOS - 文件與數據(File & Data)


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];

}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM