服務器返回兩層數組嵌套字典:
(
( { 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
將數據解析下沉到模型層,控制器代碼更乾淨,且便於單元測試和數據結構變更適配。