¿Podría explicar varios usos de la ruta clave?

I had a result that i wanted (getting max value.) with using keypath feature by someone's help.

The code : getting a max value

NSNumber *number1 = [[NSNumber alloc]initWithInt:10];
NSNumber *number2 = [[NSNumber alloc]initWithInt:20];
NSNumber *number3 = [[NSNumber alloc]initWithInt:30];
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:number1, number2, number3, nil];
NSNumber *result = [array valueForKeyPath:@"@min.intValue"];

I wonder about various usage of keypath.

Below are questions.

Q1) How to get an instance of having a max value of int_test property?

Q2) How to get a max value of int_test property in Just instances?

Just *test1 = [[Just alloc]init];
test1.int_test = 10;

Just *test2 = [[Just alloc]init];
test2.int_test = 20;

Just *test3 = [[Just alloc]init];
test3.int_test = 30;

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:test1, test2, test3, nil];

NSLog(@"%@",[array valueForKeyPath:@"?????"]); <= Q1)
NSLog(@"%d",[array valueForKeyPath:@"?????"]); <= Q2)

preguntado el 01 de febrero de 12 a las 14:02

1 Respuestas

Nota: Untested code ahead. Ideally, I'd test this before posting as an answer, but I don't have time to do that just now. I believe the code is correct conceptually, but you may need to tweak it to get it to work. If you find any errors, please let me know so that I can make the necessary corrections.

Q2) How to get a max value of int_test property in Just instances?

Utilizar esta:

int max = [array valueForKeyPath:@"@max.int_value"].intValue;

Q1) How to get an instance of having a max value of int_test property?

Use the NSArray method -indexOfObjectPassingTest: Me gusta esto:

int max = [array valueForKeyPath:@"@max.int_value"].intValue;
BOOL (^MaxTest)(id, NSUInteger, BOOL) = ^(id obj, NSUInteger idx, BOOL *stop) {
    BOOL isMax = NO;
    if (obj.int_test == max) {
        isMax = YES;
        *stop = YES;
    }
    return isMax;
}
NSUInteger testMaxIndex = [array indexOfObjectPassingTest:MaxTest];
Just testMax = [array objectAtIndex:testMaxIndex];

Respondido 01 Feb 12, 19:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.