[英]Nested NSArray / NSDictionary issue
I have an NSArray
containing several NSDictionaries
. 我有一个包含几个
NSDictionaries
的NSArray
。
I have an NSString
containing an ID string. 我有一个包含ID字符串的
NSString
。
What I'm trying to do is iterate through the NSDictionaries
until I find the object that matches the NSString
. 我想做的是遍历
NSDictionaries
直到找到与NSString
匹配的对象。 Then I want to return the entire NSDictionary
. 然后我想退回整个
NSDictionary
。
I'm fairly new to iPhone development, so I'm probably missing something obvious... Thanks in advance. 我刚开始接触iPhone,所以我可能缺少明显的东西。 :)
:)
Edit, here's the .plist
file that gets saved out: 编辑,这是保存下来的
.plist
文件:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<array>
<dict>
<key>date</key>
<string>2011/05/20</string>
<key>id</key>
<string>1282007740</string>
<key>name</key>
<string>Test item name</string>
<key>niceDate</key>
<string>May 20, 2011</string>
</dict>
<dict>
<key>date</key>
<string>2010/08/15</string>
<key>id</key>
<string>1282075925</string>
<key>name</key>
<string>Test. Nothing to see here.</string>
<key>niceDate</key>
<string>Aug 15, 2010</string>
</dict>
</array>
</plist>
Let's say my NSString is "1282075925". 假设我的NSString是“ 1282075925”。 I want to get the dictionary with the id key that matches.
我想获取具有匹配ID键的字典。
This code should do what you want - at the end, dict
will either point to the NSDictionary
you are searching for, or it will be nil
if there was no matching dictionary. 这段代码应该可以满足您的要求-最后,
dict
将指向您正在搜索的NSDictionary
,或者如果没有匹配的字典,它将为nil
。
// (These are assumed to exist)
NSArray *dictionaries;
NSString *idToFind;
NSDictionary *dict = nil;
for (NSDictionary *aDict in dictionaries) {
if ([[aDict objectForKey:@"id"] isEqualToString:idToFind]) {
dict = aDict;
break;
}
}
If you are searching for @"12345", with a key of @"id" 如果要搜索@“ 12345”,则其键为@“ id”
for (NSDictionary* dictionary in array1) {
id value = [dictionary valueForKey:@"id"];
if ([value isKindOfClass:[NSString class]]) {
NSString* string = (NSString*) value;
if ([string isEqualToString:@"12345"]) {
return dictionary;
}
}
}
return nil;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.