我的应用程序中有一个PLIST文件,其中包含各种配置数据。其中一些数据是用于访问服务器的URL。此服务器托管我们代码的几个不同版本的JSON文件。我想要做的是在PLIST文件中有一个具有版本的值,然后能够从其他值中引用它。因此,plist中的URL值可以是版本${https://www.company.com/}/jsonfile.svc(其中${VERSION}是同一plist文件中的不同键)。
发布于 2013-04-16 05:08:15
正如bshirley提到的,没有什么是自动的,但Objective-C可以帮助你做到这一点。下面是一个名为VariableExpansion的NSDictionary类别的简单实现,它演示了如何实现这一点(请注意,这并没有经过充分的测试,但主要用于演示如何使其自动化。此外,expandedObjectForKey假定您正在处理NSString,因此您可能需要对其进行一些调整。
// 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];发布于 2013-04-16 04:15:53
你试过什么吗?这非常简单,就像您提到的那样,将其转换为特殊使用的方法:stringByReplacingOccurrencesOfString:。
https://stackoverflow.com/questions/16023731
复制相似问题