从 NSMutableArray 收集特定对象的计数

发布于 2024-10-18 03:59:05 字数 255 浏览 5 评论 0原文

嘿伙计们&女孩们, 我想知道如何找到数组中特定类型对象的对象计数。 例如,我在 NSMutableArray 中的随机位置有 6 个“云”,在这个 NSMutableArray 中我也有 4 个“龙”。

我怎样才能得到整数6?

我的想法是这样的:

int z = [[SomeClass *clouds in _somearray] count];

任何帮助将不胜感激。 谢谢, 奥利弗.

Hey guys & girls,
Im wondering how I can find the object count of a specific type of object in an array.
For example, i have 6 'clouds' in NSMutableArray at random locations, I also have 4 'dragons' in this NSMutableArray.

How can i gather the integer 6?

I was thinking something along the lines of:

int z = [[SomeClass *clouds in _somearray] count];

Any assistance would be greatly appreciated.
Thnx,
Oliver.

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

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

发布评论

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

评论(3

抠脚大汉 2024-10-25 03:59:05

另一种方法是使用块:

Class cloadClass = NSClassFromString(@"Cloud");
NSArray *a = /* you array with clouds and dragons */;

NSIndexSet *clouds = [a indexesOfObjectsPassingTest: 
    ^(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isKindOfClass:cloadClass];
    }];

// now we can count clouds
NSLog(@"%d", [clouds count]);

// but also we now can return our clouds immediately and
NSLog(@"%@", [a objectsAtIndexes:clouds]);

Yet another way is in using blocks:

Class cloadClass = NSClassFromString(@"Cloud");
NSArray *a = /* you array with clouds and dragons */;

NSIndexSet *clouds = [a indexesOfObjectsPassingTest: 
    ^(id obj, NSUInteger idx, BOOL *stop) {
        return [obj isKindOfClass:cloadClass];
    }];

// now we can count clouds
NSLog(@"%d", [clouds count]);

// but also we now can return our clouds immediately and
NSLog(@"%@", [a objectsAtIndexes:clouds]);
熟人话多 2024-10-25 03:59:05
int result = 0;
for (NSObject *object in _somearray) {
    if ([object isKindOfClass:[SomeClass class]])
        result++;
}

result 是您要查找的计数

int result = 0;
for (NSObject *object in _somearray) {
    if ([object isKindOfClass:[SomeClass class]])
        result++;
}

result is the count you are looking for

堇年纸鸢 2024-10-25 03:59:05

如果您正在查找对象的特定实例出现的次数,您可以这样做:

NSCountedSet *counts = [NSCountedSet setWithArray:myArrayOfObjects];
NSUInteger count = [counts countForObject:myObject];

否则您只需手动循环数组并进行计数。

If you're looking for how many times a specific instance of an object appears, you can do:

NSCountedSet *counts = [NSCountedSet setWithArray:myArrayOfObjects];
NSUInteger count = [counts countForObject:myObject];

Otherwise you'd just have to loop through the array manually and count.

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