您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 移動應用的通用資料流:從網路請求到持久化再到 UI

編輯:iOS 開發綜合

幾乎每個列表頁的資料流都是同一套:觸發 → 發請求 → 解析 → 存檔 → 刷新 UI;失敗時則退回讀取本地資料。以下用一個 Ruby China 節點列表的例子,把六個階段各自拆成獨立方法,並用不同顏色的標籤標示目前走到哪一步,方便觀察流程。

1. 觸發

- (IBAction)clickStart:(id)sender {
    for (int i = 0; i < 6; i++) {
        UILabel *label = (UILabel *)[self.view viewWithTag:i + 10000];
        label.textColor = [UIColor blueColor];
    }
    [self performSelector:@selector(start) withObject:nil afterDelay:1];
}

把六個階段標籤統一設為藍色(未開始),再延遲一秒啟動,視覺上就能追著顏色跑流程。

2. 發送請求

-(void)httpGET {
    UILabel *label = (UILabel *)[self.view viewWithTag:1 + 10000];
    label.textColor = [UIColor redColor];

    __block id myself = self;

    HttpRequest *request = [self.entityModel.requestHelper get:@"api/nodes.json"];

    [request succeed:^(HttpRequest *op) {
        UILabel *label = (UILabel *)[self.view viewWithTag:2 + 10000];
        label.textColor = [UIColor redColor];

        if ([op isCachedResponse]) {
            NSLog(@"Data from cache %@", [op responseString]);
            [myself parseData:[op responseString] isCachedResponse:YES];
        } else {
            NSLog(@"Data from server %@", [op responseString]);
            [myself parseData:[op responseString] isCachedResponse:NO];
        }
    } failed:^(HttpRequest *op, NSError *err) {
        NSString *str = [NSString stringWithFormat:@"Request error : %@",
                         [err localizedDescription]];
        NSLog(@"%@", str);
        [self loadFromDBProcess];
    }];

    [self.entityModel.requestHelper submit:request];
}

這裡有兩個細節值得注意。一是 requestHelper 把「是否來自快取」區分出來,讓上層能決定要不要重新存檔;二是 __block id myself = self; 這個寫法,是為了避開 block 直接強引用 self 造成的循環引用(在 ARC 下應改用 __weak typeof(self) weakSelf = self)。失敗時呼叫 loadFromDBProcess 是離線友善設計的關鍵——網路不可用時仍有內容可看。

3. 解析

-(void)parseData:(NSString *)str isCachedResponse:(BOOL)isCachedResponse {
    UILabel *label = (UILabel *)[self.view viewWithTag:3 + 10000];
    label.textColor = [UIColor redColor];

    self.model = [str toModels:[RubyChinaNodeEntity class]];
    [self performSelector:@selector(refreshUI) withObject:nil afterDelay:1];

    if (isCachedResponse) {
        ;
    } else {
        [self performSelector:@selector(saveToDBProcess) withObject:nil afterDelay:1];
    }
}

toModels: 是專案自行擴充的 NSString 分類,把 JSON 字串直接轉為模型陣列。若資料來自快取,就跳過存檔,避免無意義的寫入。

4. 持久化

-(void)saveToDBProcess {
    UILabel *label = (UILabel *)[self.view viewWithTag:4 + 10000];
    label.textColor = [UIColor redColor];

    PERF_ENTER_(saveAllToDB)
    [self.model saveAllToDB];
    PERF_LEAVE_(saveAllToDB)
}

PERF_ENTER_/PERF_LEAVE_ 是一對效能計時巨集,用來量測寫入耗時。在持久化這類容易成為瓶頸的環節埋點,是很值得養成的習慣。

5. 刷新 UI

-(void)refreshUI {
    UILabel *label = (UILabel *)[self.view viewWithTag:5 + 10000];
    label.textColor = [UIColor redColor];

    if (self.model && self.model.count > 0) {
        NSString *str = [[self.model objectAtIndex:0] YYJSONString];
        SHOWMBProgressHUD(@"Data", str, nil, NO, 3);
    }
}

6. 讀取資料庫

-(void)loadFromDBProcess {
    self.model = [NSArray loadFromDBWithClass:[RubyChinaNodeEntity class]];
    [self performSelector:@selector(refreshUI) withObject:nil afterDelay:1];
}

把這六段放在一起,其實就是一份「列表頁資料流的樣板」。值得學的不是那些自訂巨集,而是分層的順序:網路層負責取字串、模型層負責解析、儲存層負責寫入、UI 層只負責顯示,每一層不知道自己以外的細節。実務上還可以再加兩塊:一是把 UI 更新統一 dispatch 回主線程(若請求回呼不在主線程),二是加上下拉刷新與分頁載入,讓這套流程在真實產品中完整可用。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved