我想製作一個包含我們的商店的桌面視圖 - 按城市劃分。UITableView部分的動態標題
tableview的數據通過我的webapp的API收集在一個json字符串中,我使用開源的Objective-c JSON框架解析NSDictionary。
的反應看起來有點像這樣:
{
city = "Amsterdam";
code = erbur;
title = "Shop Lorem";
},
{
city = "Amsterdam";
code = kadap;
title = "Shop Ipsum";
},
{
city = "Rotterdam";
code = elaml;
title = "Shop Dolor";
},
{
city = "Delft";
code = lamla;
title = "Shop Sit";
},
{
city = "Rotterdam";
code = koppa;
title = "Shop Amet";
},
我最初的計劃是創建每個城市一個陣列,這些陣列存儲在字典比,與titleForHeaderInSection:
命名的章節時,做這樣的事情:
if (section == 0) {
return @"Amsterdam"; }
else if (section == 1) {
return @"Roteterdam";
} Etc..
這裏的問題:我們都相當迅速擴大,我不想更新我的應用程序每次我們在一個新的城市開店。所以我不能硬編碼城市的陣列。
什麼是正確的方式來確保新城市中的新店顯示在正確的城市內的表格視圖中?
在此先感謝!
編輯 這裏是我的代碼:
- (void)getLocData
{
SBJSON *parser = [[SBJSON alloc] init];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://foo.bar/locaties/lijst"]];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *statuses = [parser objectWithString:json_string error:nil];
//the abive works
[statusesArray release];
statusesArray = statuses;
NSArray *cityNames = [statuses valueForKey:@"code"];
[locationCodes release];
locationCodes = cityNames;
- (void)viewDidLoad {
[super viewDidLoad];
[self getLocData];
//titel
self.title = NSLocalizedString(@"Locaties", @"Locaties - Steden");
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [locationCodes count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return 1;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [locationCodes objectAtIndex:section];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSString *cityName = [locationCodes objectAtIndex:[indexPath section]];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"code like %@", cityName];
NSArray *filteredShops = [statusesArray filteredArrayUsingPredicate:predicate];
NSDictionary *currentShop = [filteredShops objectAtIndex:[indexPath row]];
NSString *cellTitle = [currentShop objectForKey:@"title"];
cell.textlabel.text = cellTitle;
return cell;
}
主題應該是UITableView,對嗎? – 2011-02-08 18:31:10
糟糕,你是對的。編輯.. – 2011-02-08 18:46:12