gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:10:30 26 4
gpt4 key购买 nike

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

最佳答案

正如 bshirley 所提到的,没有什么是自动的,但 Objective-C 可以帮助您。下面是一个名为 VariableExpansionNSDictionary 类别的简单实现,演示了如何实现它(请注意,这没有经过全面测试,但主要用于演示您可以制作的方式这是自动的。此外,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];

关于iOS - PLIST - 从 plist 中访问其他 plist 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16023731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com