Pregunta

I have a nsmutablearray called temparray. That nsmutablearray has a key called "mountains". The objects inside the key mountains are 14, 12, 16, 20, 20, 20. How do I add up the objects inside the key "mountains" only for objects equal to a string like @"20"?

Update 2: Due to popular demand, I have printed out the nsmutablearray using nslog. It will show you exactly what I have described all along.

2014-03-16 21:36:16.493 Labresults[7213:60b] temparray (
        {
        mountains = "20";
        cookies = "11";
        picturid = "4";
    }
        {
        mountains = "20";
        cookies = "2";
        picturid = "6";
    }
        {
        mountains = "32";
        cookies = "2";
        picturid = "9";
    }
)

Update: Here is what I have so far. It works, but I have to make it far simpler and quicker for it to work faster than a minute.

    -(void)mountainloop {
        if (fillerstring == NULL) {
            int x = 0;
            _first = NULL;
            _second = NULL;

            NSDictionary *itemAtIndex =(NSDictionary *)[temparray objectAtIndex:x];
            _first = [itemAtIndex objectForKey:@"mountains"];
            if ([_first isEqualToString:@"20"]) {
            float a = [_first floatValue];
            k = [NSNumber numberWithFloat: a];
}     
            x = x + 2;//make +2
            if (([temparray count] < x)) {
                _allmonthdail.text = [NSString stringWithFormat:@"%.2f", _allmonthdail.text, a];
                temparray = NULL;         
            }
            else {
                x = x - 1;
                e = &x ;
                fillerstring = @"noo";       
                [self mountainloop];
            } 

        }
        else {
            int x= *(e);
            _first = NULL;

            NSDictionary *itemAtIndex =(NSDictionary *)[temparray objectAtIndex:x];
            _first = [itemAtIndex objectForKey:@"mountains"];
            if ([_first isEqualToString:@"20"]) {

            float a = [_first floatValue];
            float myfloatvalue = [k  floatValue];
            k = [NSNumber numberWithFloat: a + myfloatvalue];  
}       
            x = x + 2;
            if (([temparray count] < x)) {           
                float u = [k floatValue];
                _allmonthdail.text = [NSString stringWithFormat:@"%.2f", _allmonthdail.text, u];
                temparray = NULL;         
            }
            else {
                x = x - 1;
                e = &x ;
                fillerstring = @"noo";               
                [self mountainloop];
            }}      
    }
¿Fue útil?

Solución

Try this,

NSIndexSet *indxs = [temparray indexesOfObjectsPassingTest:^BOOL(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
        return [obj[@"mountain"] isEqualToString:@"20"];
    }];

NSInteger sum = 20 * indxs.count;
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top