How to filter NSDictionary by value and create new NSDictionary from that?

2.9k views Asked by At

I have a list of dates in a format yyyyMMdd as long. I've created dictionary with key yyyyMMdd and value yyyyMM (as NSString). I need to filter that NSDictionary (by value) and create a new one form that. How to do that?

REMARK: I suppose that this is duplicate, but I can not figure out how to do that.

EDIT: I don't understand why my question is marked as duplicate with questions solving my problem is C#? As I know (my knowledge in objective-C is limited) the syntax is very different. Also I don't know about linq or lambdas in objective-C.

3

There are 3 answers

5
Ken Thomases On BEST ANSWER

There are a number of ways to do this (including the one you consider noobish). Here's one:

NSArray* keys = [dict keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop){
    // return YES or NO depending on whether the value (in "obj") passes your test
}];
NSDictionary* newDict = [dict dictionaryWithValuesForKeys:keys];

Be warned that -dictionaryWithValuesForKeys:, when applied to a dictionary, can do something unexpected for keys starting with "@". That's because it's implemented in terms of -valueForKey: and NSDictionary's implementation of that method treats such keys specially. Shouldn't matter for the case you described.

0
d4Rk On

So I'm still not 100% sure about what you want to do, and why you want to do it this way.

But check this out:

// create a new dict for this example, you can just use ur existing one
NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"201506", @"20150601",
                                                                  @"201505", @"20150501", nil];

NSArray *resultArray = [[dict allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF == %@", @"201506"]];

// testing the output
NSLog(@"%@", resultArray);

You don't have a dictionary in the end, but an array with your filtered values from the dictionary. Maybe you'll have to adjust the predicate for your needs and put the resultArray stuff back into a dictionary, but I've no idea, how your result should look like.

0
David On
 //old dictionary stores @{date: string} ,where data = NSDate; string = NSString from NSDate
 NSMutableArray * storedValues = [[oldDictionary allValues]mutableCopy];
 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF > %@",[NSDate date]];
 NSArray *sortedArray = [storedValues filteredArrayUsingPredicate:predicate];


  NSMutableDictionary *newDictionary = [NSMutableDictionary dictionary];
  for(NSDate *date in sortedArray) {
      NSArray *keys = [oldDictionary allKeysForObject:date];
      NSString *key = keys.firstObject;
     [newDictionary setObject:date forKey:key];
}