Deleting the keys and values in NSDictionaries more than the value 100.000 kilometers

53 views Asked by At

I am having a trouble with NSDictionary am adding value as a kilo meters and name as a key this is how am giving

NSDictionary * dd = [NSDictionary dictionaryWithObjects:locationKMArray forKeys:nameArray];
NSLog(@"%@",dd);

This is how outputs looks like

name1 = 1.011115;
name2 = 55.14256;
name3 = 150.48752;
name4 = 22.48668;
:
:

looks like this now i want to print only less than 100.000 kilo meters how can i do this

3

There are 3 answers

2
Bannings On BEST ANSWER

You can filter the dd as below:

NSSet *keys = [dd keysOfEntriesPassingTest:^BOOL(NSString *key, NSNumber *obj, BOOL *stop) {
    return obj.floatValue < 10000;
}];
NSLog(@"%@", keys);

[keys enumerateObjectsUsingBlock:^(NSString *key, BOOL *stop) {
    NSLog(@"%@", dd[key]);
}];
0
Cristian Pena On

You can do it like this

NSDictionary* dict = [NSDictionary dictionaryWithObjects:locationKMArray forKeys:nameArray];
NSArray*keys=[dict allKeys];
for (NSString* key in keys) {
    int km = [dict objectForKey:key];
    if (km > 10000) {
        NSLog(@"%d" km);
    }
}

I don't know if you entered the kms actually with the "km" string or just as ints or longs. Adjust as needed.

Regards

0
Nimit Parekh On
NSMutableDictionary *dic = [@{@"name1":@"1.011115 km",@"name2":@"55.14256 km",@"name3":@"150.48752 km",@"name4":@"22.48668 km"}mutableCopy];
for (NSString* key in dic) {
    NSString *value = [dic objectForKey:key];
    NSArray *array = [value componentsSeparatedByString:@" "];
    double km = [[array objectAtIndex:0] doubleValue];

    if (km > 100) {
        [dic removeObjectForKey:key];
    }
}
NSLog(@"%@",dic);