[英]how to make a new NSDictionary from a NSDictionary where key = x
[英]How to filter NSDictionary by value and create new NSDictionary from that?
我有日期的列表的格式yyyyMMdd
为long
。 我用键 yyyyMMdd
和值 yyyyMM
(作为NSString
)创建了字典。 我需要过滤该NSDictionary
(按value
)并创建一个新的表单。 怎么做?
备注:我想这是重复的,但是我不知道该怎么做。
编辑:我不明白为什么我的问题被标记为重复,与解决我的问题的问题是C#? 据我所知(我对Objective-C的了解有限),语法有很大不同。 我也不知道Objective-C中的linq
或lambdas
。
有多种方法可以做到这一点(包括您认为不理想的一种方法)。 这是一个:
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];
请注意,将-dictionaryWithValuesForKeys:
应用于字典时,可能会对以“ @”开头的键执行意外操作。 这是因为它是根据-valueForKey:
实现的,而该方法的NSDictionary
的实现会特别对待此类键。 与您描述的情况无关紧要。
因此,我仍然不是100%地确定您想做什么以及为什么要这样做。
但是检查一下:
// 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);
最后没有字典,而是一个包含字典中过滤值的数组。 也许您必须根据需要调整谓词,然后将resultArray的内容放回字典中,但是我不知道结果如何。
//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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.