复制没有空值的 NSDictionary?

发布于 2024-10-06 03:23:38 字数 218 浏览 0 评论 0原文

我正在尝试使用 dictionaryWithDictionary 方法创建一个 NSDictionary 。但是,我的第一个 NSDictionary A 可能有一些带有空值的键。如何创建没有任何带空值的键的 B?我做所有这些都是为了用与 NSDictionary 中每个非空键对应的行填充 UITableView

I'm trying to create an NSDictionary with the dictionaryWithDictionary method. However, my first NSDictionary A may have some keys with empty values. How can I create B that doesn't have any keys with empty values? I'm doing all of this for the purposes of populating a UITableView with rows that correspond to each non-empty key in the NSDictionary.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小清晰的声音 2024-10-13 03:23:38

像这样的事情怎么样:

NSMutableDictionary *destDictionary = [NSMutableDictionary dictionaryWithCapacity:[sourceDictionary count]];
NSEnumerator *keyEnumerator = [[sourceDictionary allKeys] objectEnumerator];
id key;
while ( key = [keyEnumerator nextObject] )
    {
    NSString *object = [sourceDictionary objectForKey:key];
    if ([object length] == 0)
        continue;
    [destDictionary setObject:object forKey:key];
    }

How about something like this:

NSMutableDictionary *destDictionary = [NSMutableDictionary dictionaryWithCapacity:[sourceDictionary count]];
NSEnumerator *keyEnumerator = [[sourceDictionary allKeys] objectEnumerator];
id key;
while ( key = [keyEnumerator nextObject] )
    {
    NSString *object = [sourceDictionary objectForKey:key];
    if ([object length] == 0)
        continue;
    [destDictionary setObject:object forKey:key];
    }
穿越时光隧道 2024-10-13 03:23:38

您还可以使用块测试,过滤掉其值具有长度的键,并从中创建新的字典。

NSSet *keySet = [dictionary keysOfEntriesPassingTest:
                 ^(id key, id obj, BOOL *stop) {
                   return (BOOL)[obj length];
                 }];

NSArray *keys = [keySet allObjects];
NSArray *nonEmptyObjects = [dictionary objectsForKeys:keys notFoundMarker:@""];
NSDictionary *newDict = [NSDictionary dictionaryWithObjects:nonEmptyObjects
                                                    forKeys:keys];

You could also use a block test, filtering out the keys whose values have a length and create your new dictionary from that.

NSSet *keySet = [dictionary keysOfEntriesPassingTest:
                 ^(id key, id obj, BOOL *stop) {
                   return (BOOL)[obj length];
                 }];

NSArray *keys = [keySet allObjects];
NSArray *nonEmptyObjects = [dictionary objectsForKeys:keys notFoundMarker:@""];
NSDictionary *newDict = [NSDictionary dictionaryWithObjects:nonEmptyObjects
                                                    forKeys:keys];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文