字典中查找空值的捷径技术? [英] short cut technique for finding null value from Dictionary?

查看:63
本文介绍了字典中查找空值的捷径技术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在nsmutabledictornary中有100个键和值,我想检查任何值是否为null.您有任何简短的功能或技巧吗?

I have 100 key and value in nsmutabledictornary and i want to check that any value have null or not. Do you have any short function or technique?

我不想使用多个行代码,例如检查每个键和值.您的回答将不胜感激.

I don't want to multiple line code like check every key and value. Your answer would be appreciated.

推荐答案

此代码将为您提供一组具有(非)空值的键.您无法在字典中存储实际的nil值,因此假定为[NSNull null].谓词对于任何其他条件都是微不足道的.

This code will give you the set of keys which have (non)null values. You can't store actual nil values in a dictionary, so [NSNull null] is assumed. The predicate is trivially alterable to any other condition.

NSDictionary *d = @{ @"a" : @"1", @"b" : [NSNull null] };

NSSet *nullKeys = [d keysOfEntriesPassingTest:^BOOL(NSString *key, id obj, BOOL *stop) {
    return [d[key] isKindOfClass:[NSNull class]];
}];

NSSet *nonnullKeys = [d keysOfEntriesPassingTest:^BOOL(NSString *key, id obj, BOOL *stop) {
    return [d[key] isKindOfClass:[NSNull class]] == NO;
}];

如果需要,您可以从此处使用键生成相应的字典.

From here, you can use the keys to generate a corresponding dictionary, if needed.

NSMutableDictionary *nonNullDict = [NSMutableDictionary dictionary];
[d enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
    if ([nonnullKeys contains:key]) {
        nonNullDict[key] = obj;
    }
}];

如果您不需要单独的键列表,而只需要过滤后的字典,请跳过第一步,然后将第二部分修改如下:

If you don't need a separate list of keys, and just need the filtered dictionary, skip the first step and modify the second part to read as follows:

NSMutableDictionary *nonNullDict = [NSMutableDictionary dictionary];
[d enumerateKeysAndObjectsUsingBlock:^(NSString *key, id obj, BOOL *stop) {
    if ([obj isKindOfClass:[NSNull null]] == NO) {
        nonNullDict[key] = obj;
    }
}];

这篇关于字典中查找空值的捷径技术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆