2013-04-15 134 views
2

我的應用程序中有一個PLIST文件,其中包含各種配置數據。其中一些數據是用於訪問服務器的URL。該服務器託管我們代碼的幾個不同版本的JSON文件。我想要做的是在PLIST文件中有一個值,它具有版本,然後可以從其他值引用它。因此,plist中的url值可以是https://www.company.com/ $ {VERSION} /jsonfile.svc(其中$ {VERSION}是與同一個plist文件中的不同關鍵字)。iOS - PLIST - 從plist中訪問其他plist值

回答

0

你有試過什麼嗎?這是相當直接的,把它轉換成你所提到的特殊用法:stringByReplacingOccurrencesOfString:

+0

現在我拉出的值,並從代碼內構造字符串。我希望這個自動完成,因此當我拉取值時,根據plist文件中的值插入版本號。 – rplankenhorn

+0

沒有什麼「自動的」讓你利用,從文件中加載字典,使其變得可變,迭代值並替換你感興趣的值。如果這是你將來要使用的東西,使其成爲'NSMutableDictionary'的一個類別,以便您可以在別處使用它 – bshirley

3

由於bshirley提到沒有什麼是自動的,但Objective-C可以幫助你。下面是一個NSDictionary類別的簡單實現,其名稱爲VariableExpansion,它演示瞭如何實現(請注意,這並未完全測試,但主要用於演示如何自動進行此操作。另外,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];