我想知道是否有办法缩短我的CountryViewController.m,因为每次添加新国家时我都会添加其他if语句。
我正在使用推送新表视图的UITableViews。
RootViewController.m
- (void)viewDidLoad
{
[super viewDidLoad];
self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
ASIA = [[NSMutableArray alloc] init];
EU = [[NSMutableArray alloc] init];
[ASIA addObject: @"China"];
[ASIA addObject: @"Japan"];
[ASIA addObject: @"Korea"];
[EU addObject: @"France"];
[EU addObject: @"Italy"];
[EU addObject: @"Switzerland"];
self.title = @"Continent";
}
CountryViewController.m
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
if ([self.title isEqualToString: @"China"]) {
_listOfCities = [[NSMutableArray alloc] init];
[_listOfCities addObject: @"Beijing"];
[_listOfCities addObject: @"Hong Kong"];
}
else if ([self.title isEqualToString: @"Japan"]){
_listOfCities = [[NSMutableArray alloc] init];
[_listOfCities addObject: @"Tokyo"];
}
else if ([self.title isEqualToString: @"Korea"]){
_listOfCities = [[NSMutableArray alloc] init];
[_listOfCities addObject: @"Seoul"];
}
else if ([self.title isEqualToString: @"France"]){
_listOfCities = [[NSMutableArray alloc] init];
[_listOfCities addObject: @"Paris"];
[_listOfCities addObject: @"Versailles"];
}
else if ([self.title isEqualToString: @"Italy"]){
_listOfCities = [[NSMutableArray alloc] init];
[_listOfCities addObject: @"Rome"];
}
else if ([self.title isEqualToString: @"Switzerland"]){
_listOfCities = [[NSMutableArray alloc] init];
[_listOfCities addObject: @"Bern"];
}
[self.tableView reloadData];
}
答案 0 :(得分:4)
一种简单的方法是使用property list并将其作为捆绑资源包含(即将其添加到您的项目中)。
例如,如果您的属性列表如下所示:
然后您可以使用
加载它countries = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"CountryData" ofType:@"plist"]];
并将其用作普通字典或数组,即
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];
NSString* countryName = self.title;
NSDictionary* country = [countries objectForKey:countryName];
NSArray* cities = [country objectForKey:@"Cities"];
NSString* continent = [country objectForKey:@"Continent"];
_listOfCities = cities;
[self.tableView reloadData];
}
可以在XCode中轻松编辑Plist文件。