gpt4 book ai didi

iphone - 在 iPhone sdk 中搜索数组中的值

转载 作者:可可西里 更新时间:2023-11-01 06:24:55 24 4
gpt4 key购买 nike

我有这样的数组:

(
{
id=1;
Title="AAAA";
period_id=1;
},
{
id=2;
Title="BBBB";
period_id=2;
},
{
id=3;
Title="CCCC";
period_id=2;
},
{
id=4;
Title="DDDD";
period_id=2;
},
{
id=5;
Title="EEEE";
period_id=3;
},
)

问题:如何知道Period_id=2在数组中出现了多次?

帮我解决这个问题。

谢谢,

最佳答案

有很多方法可以做到这一点,其中一些在这里..

答:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"period_id == %@", @"2"];
NSArray *newArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%d", [newArray count]);

乙:

NSMutableArray *newArray = [[NSMutableArray alloc] init];
for (id obj in array)
{
if([obj[@"period_id"] isEqualToString:@"2"]){
[newArray addObject:obj];
}
}
NSLog(@"%d", [newArray count]);

C:

NSArray *allIds = [array valueForKey:@"period_id"];
NSCountedSet *set = [[NSCountedSet alloc] initWithArray:allIds];
for (id item in set)
{
NSLog(@"period_id=%@, Count=%d", item,[set countForObject:item]);
}

D:

NSArray *allIds = [array valueForKey:@"period_id"];
__block NSMutableArray *newArray = [[NSMutableArray alloc] init];
NSString *valueToCheck = @"2";
[allIds enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if([obj isEqualToString:valueToCheck])
[newArray addObject:obj];
}];
NSLog(@"%d", [newArray count]);

E:

NSIndexSet *indexes = [array indexesOfObjectsPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [[obj objectForKey:@"period_id"] isEqualToString:@"2"];
}];
NSArray *newArray = [array objectsAtIndexes:indexes];
NSLog(@"%d", [newArray count]);

关于iphone - 在 iPhone sdk 中搜索数组中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18051511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com