有没有办法缩短我的CountryViewController.m没有硬编码?

时间:2012-10-10 16:34:44

标签: iphone ios ios5

我想知道是否有办法缩短我的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];
}

1 个答案:

答案 0 :(得分:4)

一种简单的方法是使用property list并将其作为捆绑资源包含(即将其添加到您的项目中)。

例如,如果您的属性列表如下所示: enter image description here

然后您可以使用

加载它
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文件。