本文以實際專案為基礎,主要透過程式碼搭配註解來說明。這個 MyData 類別幾乎每個專案都用得上,把開發中常見的功能全部封裝在一起,讓工程開發多一個可參考的選擇。以下依序說明各項能力。
1. 判斷 iPhone 的網路狀態;
2. 判斷 iOS 版本(是否大於等於 iOS 7);
3. 圖片緩存處理;
4. GET / POST 的下載與上傳請求;
5. 加密手段(MD5);
6. 資料解析(JSON / XML)。
把各張資料表的建表、新增、讀取、刪除語句都定義成巨集,便於統一維護。以下為其中幾張表的定義:
#define MAPPINGDATA @"create table if not exists mapping(name text,title text)" // 刷圖記錄表1 #define SHAREDATA @"create table if not exists sharedata(name text,title text)" // 分享記錄表2 #define JOBDATA @"create table if not exists job(name text,title text,integral text,taskId text)" // 威客記錄表3 #define BRUSH @"create table if not exists brush(name text,taskid text,jifen text,url text)" // 刷單記錄表4 #define LEAFLETSDATA @"create table if not exists leaft(name text,taskid text,jifen text,url text)" // 傳單記錄5 // 新增資料 #define TJSJMAPPINGDATA @"insert into mapping(name,title) values(?,?)" // 讀取資料 #define DQSJMAPPINGDATA @"select *from mapping" // 刪除全部資料 #define SCSJMAPPINGDATA @"delete from mapping"
類別定義了一組 MyDataDelegate 協議,用來把下載結果、進度與錯誤資訊回傳給呼叫方:
@protocol MyDataDelegate <NSObject> @optional -(void)sendData:(NSMutableData *)datas andProgress:(float)ressNum andFilg:(NSString *)str andIndexPath:(NSIndexPath *)indexPath andError:(BOOL)error; -(void)sendData:(NSMutableData *)datas andFilg:(NSString *)str andError:(BOOL)error; @end
用 GCD 的 dispatch_once 取得唯一的系統主版本號,再據此判斷是否為 iOS 7 以上:
NSUInteger DeviceSystemMajorVersion() {
static NSUInteger _deviceSystemMajorVersion = -1;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_deviceSystemMajorVersion = [[[[[UIDevice currentDevice] systemVersion] componentsSeparatedByString:@"."] objectAtIndex:0] intValue];
});
return _deviceSystemMajorVersion;
}
圖片存放在沙盒的 Caches 目錄下的「圖片緩存」資料夾,並提供新增、判斷是否存在、讀取、刪除與計算資料夾大小的完整方法。核心概念是以 NSFileManager 判斷路徑是否存在、建立目錄、寫入或讀取檔案。
借助 CommonCrypto 的 CC_MD5 將字串轉為 MD5 雜湊:
+ (NSString *)md5:(NSString *)str {
const char *cStr = [str UTF8String];
unsigned char result[32];
CC_MD5(cStr, strlen(cStr), result);
return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15]];
}
下載透過 NSURLConnection 搭配 didReceiveResponse、didReceiveData、connectionDidFinishLoading 等回調來累積資料並回報進度;POST 則以 NSMutableURLRequest 設定 HTTPMethod 與 body 後送出。停止下載時呼叫 [connection cancel] 即可。
網路判斷使用 Reachability 檢查連線狀態;資料解析方面,JSON 可用系統的 NSJSONSerialization 或第三方 JSON.h,XML 則以 GDataXMLNode 解析出各節點並組裝成字典陣列。
資料庫存放於 Caches 目錄下的 shuJu.sqlite,並以 static sqlite3 *db 作為全域句柄。新增資料時先呼叫建表方法確保資料表存在,再用 sqlite3_prepare 搭配 sqlite3_bind_text 為問號賦值,避免 SQL 注入並提升安全性。讀取時以 sqlite3_step 逐列取出欄位組裝成字典陣列,操作完成後以 sqlite3_finalize 與 sqlite3_close 收尾。
把這些常用能力集中封裝成一個 MyData 類別,之後各頁面只需呼叫對應的類方法即可,大幅降低重複勞動,也讓專案結構更清楚。