我想知道是否有办法缩短我的 CountryViewController.m,因为每次添加新国家/地区时我都会添加另一个 else if 语句。
我正在使用一个 UITableViews 来推送一个新的表格 View 。
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)viewWillAppearBOOL)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: @"aris"];
[_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];
}
一个简单的方法是使用 property list并将其作为捆绑资源包含(即只需将其添加到您的项目中)。
例如,如果您的属性列表如下所示:
然后您可以使用
加载它countries = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource"CountryData" ofType"plist"]];
并将其用作普通字典或数组,即
- (void)viewWillAppearBOOL)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];
}
Plist 文件可以在 XCode 中轻松编辑。
关于iphone - 有没有办法在不进行硬编码的情况下缩短我的 Country ViewController.m?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12824214/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |