iOS - PLIST - 从plist中访问其他plist值

时间:2013-04-15 19:57:00

标签: ios plist

我的应用中有一个包含各种配置数据的PLIST文件。一些数据是用于访问服务器的URL。此服务器托管我们代码的几个不同版本的JSON文件。我希望能够做的是在PLIST文件中有一个具有该版本的值,然后能够从其他值引用它。因此plist中的url值可以是https://www.company.com/ $ {VERSION} /jsonfile.svc(其中$ {VERSION}是同一个plist文件中的不同键)。

2 个答案:

答案 0 :(得分:3)

正如bshirley所说,没有什么是自动的,但Objective-C可以帮助你。以下是名为NSDictionary的{​​{1}}类别的简单实现,演示了如何实现此功能(请注意,这不是经过全面测试,但主要用于演示如何自动实现此功能。此外,{ {1}}假设您正在处理VariableExpansion s,因此您可能需要对其进行一些调整。

expandedObjectForKey

最后一步的结果是NSString,表明您可以在单个值中使用多个变量。如果找不到变量,则不会触及原始字符串。

由于您使用PLIST作为源,因此请使用

中的// In file NSDictionary+VariableExpansion.h @interface NSDictionary (VariableExpansion) - (NSString*)expandedObjectForKey:(id)aKey; @end // In file NSDictionary+VariableExpansion.m #import "NSDictionary+VariableExpansion.h" @implementation NSDictionary (VariableExpansion) - (NSString*)expandedObjectForKey:(id)aKey { NSString* value = [self objectForKey:aKey]; NSError *error = NULL; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\$\\{([^\\{\\}]*)\\}" options:NSRegularExpressionCaseInsensitive error:&error]; __block NSMutableString *mutableValue = [value mutableCopy]; __block int offset = 0; [regex enumerateMatchesInString:value options:0 range:NSMakeRange(0, [value length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop) { NSRange matchRange = [match range]; matchRange.location += offset; NSString* varName = [regex replacementStringForResult:match inString:mutableValue offset:offset template:@"$1"]; NSString *varValue = [self objectForKey:varName]; if (varValue) { [mutableValue replaceCharactersInRange:matchRange withString:varValue]; // update the offset based on the replacement offset += ([varValue length] - matchRange.length); } }]; return mutableValue; } @end // To test the code, first import this category: #import "NSDictionary+VariableExpansion.h" // Sample NSDictionary. NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"http://${HOST}/${VERSION}/bla", @"URL", @"1.0", @"VERSION", @"example.com", @"HOST", nil]; // And the new method that expands any variables (if it finds them in the PLIST as well). NSLog(@"%@", [dict expandedObjectForKey:@"URL"]);
http://example.com/1.0/bla

答案 1 :(得分:0)

你试过什么吗?这是相当简单的,正如你所提到的那样转换它,特别是使用的方法:stringByReplacingOccurrencesOfString: