使用多个值创建动态NSMutableDictionary查询

时间:2012-06-09 16:42:43

标签: iphone ios templates dynamic nsmutabledictionary

我正在开发一个项目,我希望能够处理一些模板类型的消息。该模板将包含以下内容:

"{{user1}} has just created an account"

然后我有一个数据映射,它会在NSMutableDictionary中为您提供数据所在的位置:

"activity.message.status"

然后我希望能够通过拆分该字符串来查询NSMutableDictionary,以便它变成类似:

[[[myDictionary objectForKey:@"activity"] objectForKey:@"message"] objectForKey:@"status"]

只要它只是3个字符串就可以制作一些东西,但有些可能或多或少。

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:1)

实际上比将字符串拆分为键要容易得多。 Apples Key-Value-Coding可以提供你想要的。

[myDictionary valueForKeyPath:@"activity.message.status"];
  

键路径是一串点分隔键,用于指定要遍历的对象属性序列。序列中第一个键的属性是相对于接收者的,并且每个后续键相对于前一个属性的值进行评估。

     

例如,键路径address.street将从接收对象获取address属性的值,然后确定相对于地址对象的street属性。

     

Key-Value Coding Programming Guide

答案 1 :(得分:0)

你会做点什么,

NSArray *array = [@"activity.message.status" componentsSeperatedByString:@"."];

这将创建一个包含{activity,message,status)的数组。

现在你有了可以用来查询字典的数组。

[[[myDictionary objectForKey:[array objectAtIndex:0]] objectForKey:[array objectAtIndex:1]] objectForKey:[array objectAtIndex:2]];

相当于:

[[[myDictionary objectForKey:@"activity"] objectForKey:@"message"] objectForKey:@"status"];

希望这有帮助!

答案 2 :(得分:0)

我的问题不清楚我们应该如何将user1映射到activity.message.status。现在我假设你的意思是模板可能包含像"{{activity.message.status}}"这样的字符串,你希望能够解析它。

这是一个对NSMutableString进行操作的迭代,可以循环直到找不到匹配项:

NSError *error = NULL;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\{\\{.+?\\}\\}"
                              options:NSRegularExpressionCaseInsensitive
                              error:&error];
NSRange matchRange = [regex rangeOfFirstMatchInString:string
                      options:0 range:NSMakeRange(0, [string length])];
NSRange keyPathRange = NSMakeRange(matchRange.location + 2, matchRange.length - 4);
NSString *keyPath = [string substringWithRange:keyPathRange];
NSString *newSubstring = [myDictionary valueForKeyPath:keyPath];
[string replaceCharactersInRange:matchRange withString:newSubstring];

我还没有测试过这段代码。

答案 3 :(得分:0)

NSMutableDictionary上的(递归...酷)类别方法怎么样:

- (void)setObject:(id)object forCompoundKey:(NSString *)compoundKey {

    NSArray *keys = [compoundKey componentsSeparatedByString:@"."];

    if ([keys count] == 1) {
        return [self setObject:object forKey:compoundKey];
    }

    // get the first component of the key
    NSString *key = [keys objectAtIndex:0];

    // build the remaining key with the remaining components
    NSRange nextKeyRange;
    nextKeyRange.location = 1;
    nextKeyRange.length = [keys count] - 1;
    NSArray nextKeys = [keys subarrayWithRange:nextRange];
    NSString *nextKey = [nextKeys componentsJoinedByString:@"."];

    NSMutableDictionary *nextDictionary = [NSMutableDictionary dictionary];
    [self addObject:nextDictionary forKey:key];

    // now the cool part... recursion
    [nextDictionary setObject:object forCompoundKey:nextKey];
}

我没有对此进行过测试,但它通过了快速的桌面检查。 objectForCompoundKey:检索可以类似地编写。