NSDictionary+JKBlock.m 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // NSDictionary+JKBlock.m
  3. // JKCategories (https://github.com/shaojiankui/JKCategories)
  4. //
  5. // Created by Jakey on 15/5/22.
  6. // Copyright (c) 2015年 www.skyfox.org. All rights reserved.
  7. //
  8. #import "NSDictionary+JKBlock.h"
  9. @implementation NSDictionary (JKBlock)
  10. #pragma mark - RX
  11. - (void)jk_each:(void (^)(id k, id v))block {
  12. [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  13. block(key, obj);
  14. }];
  15. }
  16. - (void)jk_eachKey:(void (^)(id k))block {
  17. [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  18. block(key);
  19. }];
  20. }
  21. - (void)jk_eachValue:(void (^)(id v))block {
  22. [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  23. block(obj);
  24. }];
  25. }
  26. - (NSArray *)jk_map:(id (^)(id key, id value))block {
  27. NSMutableArray *array = [NSMutableArray array];
  28. [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  29. id object = block(key, obj);
  30. if (object) {
  31. [array addObject:object];
  32. }
  33. }];
  34. return array;
  35. }
  36. - (NSDictionary *)jk_pick:(NSArray *)keys {
  37. NSMutableDictionary *picked = [[NSMutableDictionary alloc] initWithCapacity:keys.count];
  38. [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  39. if ([keys containsObject:key]) {
  40. picked[key] = obj;
  41. }
  42. }];
  43. return picked;
  44. }
  45. - (NSDictionary *)jk_omit:(NSArray *)keys {
  46. NSMutableDictionary *omitted = [[NSMutableDictionary alloc] initWithCapacity:([self allKeys].count - keys.count)];
  47. [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
  48. if (![keys containsObject:key]) {
  49. omitted[key] = obj;
  50. }
  51. }];
  52. return omitted;
  53. }
  54. - (BOOL)jk_hasKey:(NSString *)key
  55. {
  56. return [self objectForKey:key] != nil;
  57. }
  58. @end