美文网首页
NSDictionary NSMutableDictionary

NSDictionary NSMutableDictionary

作者: QuinceyYang | 来源:发表于2018-08-07 14:17 被阅读0次

    原始字典

            NSDictionary *dict = @{@"name":@"qyang",
                                   @"age":@"28",
                                   @"sex":@"man",
                                   @"other":@"hello",
                                   };
    
    

    1、遍历与查找

            //使用代码块遍历key-value
            [dict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                NSLog(@"%@ = %@",key,obj);
                if ([obj isEqualToString:@"qyang"]) {
                    *stop = YES;
                }
            }];
    

    2、对key进行排序

            //对key进行排序
            NSArray *keysArr = [dict keysSortedByValueUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
                //
                if ([obj1 length] > [obj2 length]) {
                    return NSOrderedAscending;
                }
                else if ([obj1 length] == [obj2 length]) {
                    return NSOrderedSame;
                }
                else {
                    return NSOrderedDescending;
                }
            }];
            NSLog(@"keysArr = %@",keysArr);
    

    打印结果为

    keysArr = (
        other,
        name,
        sex,
        age
    )
    

    3、对key进行过滤

            //对key进行过滤
            NSSet *keysSet = [dict keysOfEntriesPassingTest:^BOOL(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
                return (BOOL)([obj length]>3);
            }];
            NSLog(@"keysSet = %@",keysSet);
    

    打印结果为

    keysSet = {(
        other,
        name
    )}
    

    End

    相关文章

      网友评论

          本文标题:NSDictionary NSMutableDictionary

          本文链接:https://www.haomeiwen.com/subject/jeaovftx.html