开发者

access value for key in NSDictionary using different key

开发者 https://www.devze.com 2023-02-15 13:22 出处:网络
Spent about a week using stackoverflows search but no luck... Here is what I have: 1 plist: <plist version=\"1.0\">

Spent about a week using stackoverflows search but no luck...

Here is what I have:

1 plist:

<plist version="1.0">
  <array>  
    <dict>
      <key>name</key>
      <string>Name 1</string>
      <key>abrev</key>
      <string>(HGB, ΗbA)</string>
      <key>picture</key>
      <string>first.png</string>
      <key>pictureHeight</key>
      <integer>1686</integer>
    </dict>
    <dict>
      <key>name</key>
      <string>Name 2</string>
      <key>abrev</key>
      <string> </string>
      <key>picture</key>
      <string>second.png</string>
      <key>pictureHeight</key>
      <string>396</string>
    </dict>
    <dict> 
     ...
    <dict>
  </array>
</plist>

The questions is:

How to return values for keys "picture" and "pictureHeight"

knowing the value for the key "name".

I tried something like this, but failed desperately...

//creating an array that contains the plist

dictArray = [[NSArray alloc] initWithContentsOfFile:[[NSBundle mainBundle]  
        pathForResource:@"table1" ofType:@"plist"]];

//creating an array that contains only the vlaues for key "name"

NSMutableArray *temp = [dictArray valueForKey:@"name"];

//searchedData - an NSMutableArray containing the "name" values that  
//the user searched using the searchbar

for (i=0; i<[searchedData count]; ++i) 
{
    if ([searchedData containsObject:[temp objectAtIndex:i]]) 
    {
        [开发者_如何学Gotemp removeObjectAtIndex:i];
    }
}

At the end I have an array of values for key "name" and I need to get the "picture" and "pictureHeight" to push all of this information to next view controller...

I'm looking for any fresh ideas (or maybe tutorials), because I'm not getting too far with mine...


Use a NSPredicate and NSArray's -filteredArrayUsingPredicate: method to select the dictionaries in the array where the value for key 'name' matches whatever you're looking for. Then you can query the resulting dictionary or dictionaries the usual way, i.e. using objectForKey:.

NSPredicate is very powerful and worth the time it'll take you to learn to use it, but it does require some study. If you want something that's simpler to implement but less elegant, simply iterate over the array yourself:

NSMutableArray *matches = [NSMutableArray array];
for (NSDictionary *d in searchedData) {
    if ([name isEqualToString: [d objectForKey:@"name"]]) {
        [matches addObject:d];
    }
}

Again, you end up with an array containing the dictionaries whose 'name' matches the name you're looking for, and you can get their other attributes the usual way.

0

精彩评论

暂无评论...
验证码 换一张
取 消