我目前正在使用下面的代码显示我的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"];
}
有什么建议?
您的第二位代码,只需:
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"];
}
您也可以使用字典从传入的字符串映射到关联的文件名...
,例如
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"];