iOS-PLIST-从PLIST中访问其他PLIST值
我的应用程序中有一个包含各种配置数据的PLIST文件。有些数据是用于访问服务器的URL。这个服务器为我们的代码的几个不同版本托管JSON文件。我想要做的是在PLIST文件中有一个版本的值,然后能够从其他值引用它。因此plist中的url值可以是${VERSION}/jsonfile.svc(其中${VERSION}是同一plist文件中的另一个键)。您尝试过什么吗?这是相当简单的,正如您所提到的,转换它,特别使用的方法:iOS-PLIST-从PLIST中访问其他PLIST值,ios,plist,Ios,Plist,我的应用程序中有一个包含各种配置数据的PLIST文件。有些数据是用于访问服务器的URL。这个服务器为我们的代码的几个不同版本托管JSON文件。我想要做的是在PLIST文件中有一个版本的值,然后能够从其他值引用它。因此plist中的url值可以是${VERSION}/jsonfile.svc(其中${VERSION}是同一plist文件中的另一个键)。您尝试过什么吗?这是相当简单的,正如您所提到的,转换它,特别使用的方法:stringByReplacingOccurrencesOfString:正
stringByReplacingOccurrencesOfString:
正如bshirley所提到的,除了Objective-C之外,没有什么是自动的。下面是一个名为VariableExpansion
的NSDictionary
类别的简单实现,它演示了如何实现这一功能(请注意,这尚未经过全面测试,但主要用于演示如何使其自动化。此外,expandedObjectForKey
假设您正在处理NSString
s,因此可能需要对其进行一些调整。)
// 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
显示您可以在单个值中使用多个变量。如果未找到变量,则不会在原始字符串中触及该变量
因为您使用的是PLIST作为源代码,所以请像中一样使用dictionaryWithContentsOfFile
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:plistPath];
现在我正在从代码中提取值并构造字符串。我希望在plist中自动完成此操作,因此当我提取值时,版本号将根据plist文件中的值插入。没有“自动”选项为了便于利用,请从文件中加载字典,使其可变,对值进行迭代并替换您感兴趣的值。如果您希望将来使用它,请将其作为
NSMutableDictionary
上的一个类别,以便您可以在其他地方使用它