2

我想知道是否有办法缩短我的 CountryViewController.m 因为每次添加新国家时我都会添加另一个 else 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];
}
4

1 回答 1

4

一种简单的方法是使用属性列表并将其作为捆绑资源包含(即,只需将其添加到您的项目中)。

例如,如果您的属性列表如下所示: 在此处输入图像描述

然后你可以加载它

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];
}

Plist 文件可以在 XCode 中轻松编辑。

于 2012-10-10T16:36:59.040 回答