2

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

4

2 回答 2

3

正如 bshirley 提到的,没有什么是自动的,但 Objective-C 可以帮助你。下面是一个NSDictionary名为的类别的简单实现,VariableExpansion它演示了如何实现(请注意,这没有经过全面测试,但主要用于演示您可以使其自动化的方式。另外,expandedObjectForKey假设您正在处理NSStrings 所以您可能需要稍微调整一下。

// 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-15T21:08:15.033 回答
0

你试过什么吗?这很简单,按您所说的进行转换,具体使用方法:stringByReplacingOccurrencesOfString:.

于 2013-04-15T20:15:53.280 回答