根据变量显示plist

时间:2014-01-31 13:25:33

标签: ios nsarray nsdictionary

我正在使用下面的代码显示我的plist,这有效,但这对我来说似乎效率低下,我认为有一种更清洁的方法。

if ([self.title  isEqual: @"How to wear a Kilt"]){
    NSString *path = [[NSBundle mainBundle] pathForResource:@"wearAKilt" ofType:@"plist"];
    // Load the file content and read the data into arrays
    NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    thumbImg = [dict objectForKey:@"thumbImg"];
    stepLabel = [dict objectForKey:@"stepLabel"];
    descLabel = [dict objectForKey:@"descLabel"];
    }
    // Find out the path of recipes.plist
    else if ([self.title  isEqual: @"How to tie a cravat"]){
        NSString *path = [[NSBundle mainBundle] pathForResource:@"wearACravat" ofType:@"plist"];
        // Load the file content and read the data into arrays
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
        thumbImg = [dict objectForKey:@"thumbImg"];
        stepLabel = [dict objectForKey:@"stepLabel"];
        descLabel = [dict objectForKey:@"descLabel"];
    }
    else if ([self.title  isEqual: @"How to wear a sporran"]){
        NSString *path = [[NSBundle mainBundle] pathForResource:@"wearASporran" ofType:@"plist"];
        // Load the file content and read the data into arrays
        NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
        thumbImg = [dict objectForKey:@"thumbImg"];
        stepLabel = [dict objectForKey:@"stepLabel"];
        descLabel = [dict objectForKey:@"descLabel"];
    }

我尝试在*路径上使用if语句,但是这(如预期的那样)会产生undeclared identifier path错误。

if ([self.title  isEqual: @"How to wear a Kilt"]){
    NSString *path = [[NSBundle mainBundle] pathForResource:@"wearAKilt" ofType:@"plist"];
    } else if ([self.title  isEqual: @"How to tie a cravat"]) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"wearACravat" ofType:@"plist"];
    }

有什么建议吗?

1 个答案:

答案 0 :(得分:2)

你是第二位代码,只需这样做:

NSString *path;

if ([self.title  isEqual: @"How to wear a Kilt"]){
    path = [[NSBundle mainBundle] pathForResource:@"wearAKilt" ofType:@"plist"];
} else if ([self.title  isEqual: @"How to tie a cravat"]) {
    path = [[NSBundle mainBundle] pathForResource:@"wearACravat" ofType:@"plist"];
}

您还可以使用字典从传入字符串映射到关联的文件名...

e.g。

NSDicttionary *mapping = @{
    @"How to wear a Kilt" : @"wearAKilt",
    @"How to tie a cravat" : @"wearACravat",
};

这可能是一个静态定义,应该考虑本地化。然后:

NSString *name = [mapping objectForKey:self.title];
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:@"plist"];