search the values in array in iPhone sdk
arrays, ios, iphone, objective-c
Solution
There are lots of ways to do so, Some of them are here ..
A:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"period_id == %@", @"2"];
NSArray *newArray = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%d", [newArray count]);
B:
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]);
Problem
I have the array like: ``` ( { 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; }, ) ``` Question: How can i know that `Period_id=2` is multiple times in the array? Help me solve this. Thank you,