首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

iOS 解析嵌套數組字典填充 UITableView:room_number 匹配邏輯

     編輯:程式設計綜合問答

數據結構分析

服務器返回兩層數組嵌套字典:

(
  ( { cost = 160; room_number = 1; title = "TIMBER BLINDS"; ... } ),
  ( { cost = 170; room_number = 2; title = "ROMAN BLINDS"; ... } )
)

結構:`NSArray` → `NSArray` → `NSDictionary`

正確解析邏輯

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 1. 獲取外層數組元素 (對應 section 或分組)
    NSArray *innerArray = [outerArray objectAtIndex:indexPath.row];
    
    // 2. 獲取內層字典 (假設每組只有一個對象)
    NSDictionary *itemDict = [innerArray objectAtIndex:0];
    
    // 3. 取值並類型轉換
    NSNumber *roomNum = [itemDict valueForKey:@"room_number"];
    NSString *title = [itemDict valueForKey:@"title"];
    
    // 4. 匹配邏輯 (示例:room_number 與 row 對應)
    if ([roomNum integerValue] == indexPath.row + 1) { // 注意:room_number 從 1 開始
        cell.textLabel.text = title;
    }
    
    return cell;
}

關鍵點詳解

步驟代碼說明
層級 1`outerArray[indexPath.row]`獲取第 n 組數據
層級 2`innerArray[0]`取組內第一個 (通常唯一) 字典
取值`dict[@"room_number"]`返回 NSNumber,需 `integerValue` 轉 int
匹配`roomNum.intValue == indexPath.row + 1`數組索引從 0 開始,room_number 從 1 開始

健壯性增強:防崩潰寫法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // 安全獲取數據
    if (indexPath.row >= outerArray.count) return cell;
    
    NSArray *innerArray = outerArray[indexPath.row];
    if (innerArray.count == 0) return cell;
    
    NSDictionary *item = innerArray[0];
    NSNumber *roomNum = item[@"room_number"];
    NSString *title = item[@"title"];
    
    // 空值保護
    if (roomNum && title) {
        cell.textLabel.text = title;
        // 可選:顯示 room_number 輔助調試
        // cell.detailTextLabel.text = [NSString stringWithFormat:@"Room %@", roomNum];
    }
    
    return cell;
}

架構建議:模型層轉換

控制器不應直接處理原始 JSON 結構,建議:

// Model
@interface RoomItem : NSObject
@property (nonatomic, assign) NSInteger roomNumber;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, assign) CGFloat cost;
// ... 其他屬性
+ (instancetype)itemFromDictionary:(NSDictionary *)dict;
@end

// Parser
NSArray *rawArray = ...; // 服務器數據
NSMutableArray *roomItems = [NSMutableArray array];
for (NSArray *group in rawArray) {
    for (NSDictionary *dict in group) {
        [roomItems addObject:[RoomItem itemFromDictionary:dict]];
    }
}
// 控制器直接使用 roomItems[indexPath.row].title

將數據解析下沉到模型層,控制器代碼更乾淨,且便於單元測試和數據結構變更適配。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved