Nested NSArray / NSDictionary issue
I have an NSArray
containing several NSDictionaries
.
I have an NSString
containing an ID string.
What I'm trying to do is iterate through the NSDicti开发者_Go百科onaries
until I find the object that matches the NSString
. Then I want to return the entire NSDictionary
.
I'm fairly new to iPhone development, so I'm probably missing something obvious... Thanks in advance. :)
Edit, here's the .plist
file that gets saved out:
<?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". I want to get the dictionary with the id key that matches.
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.
// (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"
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;
精彩评论