gpt4 book ai didi

objective-c - NSDictionary 中键的路径

转载 作者:行者123 更新时间:2023-12-03 17:54:07 26 4
gpt4 key购买 nike

在我的应用程序中,我需要将值插入只有最后一个路径组件的 NSDictionary 中。例如。我给定的字典是

a = 1;
b = 2;
c = 3;
d = {
e = 4;
f = 5;
g = {
h = 6;
};
};
j = {
k = 7;
};

我需要更改k的值。路径组件应为@[@"j", @"k"]。我尝试过类似的东西:

- (void)recurse:(NSDictionary*)dict keyToFound:(NSString*)ktf stack:(NSMutableArray*)stack parent:(NSString*)parent
{
for (NSString *key in [dict allKeys]) {
if ([key isEqualToString:ktf]) {
[stack insertObject:key atIndex:[stack count]];

return;
}
else {
if ([[dict valueForKey:key] isKindOfClass:[NSDictionary class]]) {
NSDictionary *d = [dict valueForKey:key];
[stack insertObject:key atIndex:[stack count]];
[self recurse:d keyToFound:ktf stack:stack parent:key];
//[stack removeObject:key];
}
}
}

}

但是,显然,这是一种错误的方式。

最佳答案

这里有两种在嵌套字典中设置值的更简单的方法。第一个假设您知道键存在并且可能是 C 标识符。在这种情况下,使用 setValue:forKeyPath: 是最好的方法。否则,函数中的简单循环(或 NSDictionary 上的方法或类别)就可以解决问题:

void setValueForPathComponentsOfDictionary(id value, NSArray *components, NSMutableDictionary *dict) {

NSMutableArray *parts = [components mutableCopy];
id lastPart = parts.lastObject;
[parts removeLastObject];

for (id part in parts) {
if (![dict respondsToSelector:@selector(objectForKey:)])
return; // Silently fail.
dict = [dict objectForKey:part];
}

if ([dict respondsToSelector:@selector(objectForKey:)])
[dict setValue:value forKey:lastPart];
}

int main (int argc, const char * argv[])
{
@autoreleasepool {

NSMutableDictionary *dict = [@{
@"a":[@{@"a":@1,@"b":@2} mutableCopy],
@"b":[@{@"a":@3,@"b":@4} mutableCopy]
} mutableCopy];

NSLog(@"Initial Dictionary: %@", dict);

[dict setValue:@9 forKeyPath:@"a.b"];
NSLog(@"After setValue:forKeyPath: %@", dict);

setValueForPathComponentsOfDictionary(@0, @[@"b",@"a"], dict);
NSLog(@"After setValueForPathComponentsOfDictionary %@", dict);
}
return 0;
}

关于objective-c - NSDictionary 中键的路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16362592/

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