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

iOS 讀取 plist 檔案:把城市清單顯示在 UITableView 上

編輯:iOS 開發綜合

plist 為什麼適合放靜態資料

plist 本質上就是一個 XML(或二進位)格式的檔案,Xcode 甚至提供了圖形化的編輯器。對於城市列表、分類選項、關卡配置這類「App 內建且不太變動」的資料,直接打包進 bundle 用 plist 存,比寫死在程式碼裡整齊,也比啟動 SQLite 輕量。

讀取資料

關鍵是 pathForResource:ofType:。這裡有個常被搞錯的地方:副檔名要寫在 resource 名稱裡、ofType 傳 nil;或者名稱只寫主檔名、ofType 傳 @"plist"。兩種都可以,但不能拆錯。

 - (void)loadData {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"citys.plist" ofType:nil];
    allCitys = [NSArray arrayWithContentsOfFile:path];
    NSLog(@"%@", allCitys);
}

arrayWithContentsOfFile: 是最快的寫法,一行搞定。若檔案很大或需要錯誤處理,則改用 NSData 搭配 NSPropertyListSerialization:

 NSData *data = [NSData dataWithContentsOfFile:path];
NSArray *list = [NSPropertyListSerialization propertyListWithData:data
    options:NSPropertyListImmutable format:NULL error:&error];

建立表格視圖

 - (void)creatTableView {
    myTableView = [[UITableView alloc]
        initWithFrame:CGRectMake(0, 20, CGRectGetWidth(self.view.frame),
                                 CGRectGetHeight(self.view.frame) - 20)
                style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.dataSource = self;
    [self.view addSubview:myTableView];
}

實作資料來源

 - (NSInteger)tableView:(UITableView *)tableView
    numberOfRowsInSection:(NSInteger)section {
    return allCitys.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *cellID = @"cityCell";

    // 先嘗試從重用佇列取得,這是大列表不卡頓的關鍵
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                    reuseIdentifier:cellID];
    }

    cell.textLabel.text = allCitys[indexPath.row][@"State"];
    return cell;
}

dequeueReusableCellWithIdentifier: 是 UITableView 效能的核心機制:螢幕上同時最多只有十幾個 cell,滾出畫面的會被回收再利用。少了它,滾動一千筆資料就會配置一千個物件,直接卡死。

點擊後的模態切換

 - (void)tableView:(UITableView *)tableView
    didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    DetailViewController *detail = [[DetailViewController alloc] init];
    detail.modalTransitionStyle = UIModalTransitionStylePartialCurl;
    [self presentViewController:detail animated:YES completion:nil];
}

模態切換適合「暫時覆蓋、用完就關」的場景,關閉時對著自己呼叫 dismissViewControllerAnimated: 即可。若頁面之間需要層級關係與返回按鈕,則該改用 UINavigationController 的 push。

兩個實務補充

第一,plist 中的 key 若宣告為 State 這種大寫開頭,要注意它與程式碼中使用的字串必須完全一致,建議統一用小駝峰命名並定義成常數。第二,arrayWithContentsOfFile: 在檔案不存在時會安靜回傳 nil 而不報錯,後續 allCitys.count 變成 0,畫面空白卻查不出原因。實務上應該先檢查 path 是否為 nil,並在 path 為空時給出明確的錯誤提示。

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