如何在 Cocoa 中访问大型 NSDictionary 的特定子集?

发布于 2024-07-11 10:24:59 字数 363 浏览 12 评论 0原文

我有一个 NSDictionary 对象,其中包含大量自定义对象。 这些对象要么属于 B 类,要么属于 C 类,两者都继承自 A 类。如果对象属于 B 类,则它们将具有一个内部标志 (kindOfCIsh),该标志将用于将来的分组。

我如何在程序的不同时间获得包含这些对象的不同分组的 NSDictionary (或 NSArray)? 在一种情况下,我会想要所有 B 对象,但在另一种情况下,我会想要所有 C 对象,加上满足 (kindOfCIsh == true) 的 B 对象。

有没有一种简单的方法来访问这些子集? 也许使用过滤谓词? 当然,我可以循环遍历整个字典并手动构建所需的子集,但我感觉有更好的方法。

任何帮助表示赞赏。

I have a single NSDictionary object which contains a large number of custom objects. The objects will either be of class B or of class C, both of which inherit from class A. If the objects are of type B, they will have an internal flag (kindOfCIsh) which will be used for future grouping.

How can I, at different times in my program, get an NSDictionary (or NSArray) that contains different groupings of those objects? In one case, I will want all of B, but another time I will want all of the C objects, plus the B objects that satisfy (kindOfCIsh == true).

Is there a simple way to get access to these subsets? Perhaps using filter predicates? I can, of course, loop through the entire dictionary and build the required subset manually, but I have a feeling that there is a better way.

Any help is appreciated.

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

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

发布评论

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

评论(2

骷髅 2024-07-18 10:24:59

[[myDictionary allValues] FilteredArrayUsingPredicate: pred];

[[myDictionary allValues] filteredArrayUsingPredicate: pred];

记忆消瘦 2024-07-18 10:24:59

您可以使用类别,

代码是这样的

@interface NSDictionary (dictionaryForClass)

  -(NSMutableDictionary *) dictionaryWithObjectsKindOfClass:(Class)myClass;

@end

@implementation NSDictionary (dictionaryForClass)

-(NSMutableDictionary *) dictionaryWithObjectsKindOfClass:(Class)myClass;
{
  NSMutableDictionary *ret = [[[NSMutableDictionary alloc] init] autorelease];

  for (id object in self) {
    if ([object isKindOfClass:myClass]) {
       [ret addObject:object];
    }  
  }  
  return ret;

}

@end

You can use categories

the code is something like this

@interface NSDictionary (dictionaryForClass)

  -(NSMutableDictionary *) dictionaryWithObjectsKindOfClass:(Class)myClass;

@end

@implementation NSDictionary (dictionaryForClass)

-(NSMutableDictionary *) dictionaryWithObjectsKindOfClass:(Class)myClass;
{
  NSMutableDictionary *ret = [[[NSMutableDictionary alloc] init] autorelease];

  for (id object in self) {
    if ([object isKindOfClass:myClass]) {
       [ret addObject:object];
    }  
  }  
  return ret;

}

@end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文