2011-03-07 6 views

Respuesta

33
NSLocationInRange(c, NSMakeRange(a, (b - a)))

Esto devuelve una BOOL si c se encuentra dentro de a y b. Sin embargo, a, byc deben estar sin firmar int. Y esto realmente no es muy guapo. Así que supongo que es mucho mejor compararme a mí mismo.

c >= a && c <= b
+0

Gracias, esto era lo que necesitaba. (NSRange) –

+1

esto no es completamente correcto, el código reprimido por esta macro es c> = a && c TtheTank

13

misma manera que en C, C++, Java, C# ...

if (theNumber >= SOME_MINIMUM_VALUE && theNumber <= SOME_MAXIMUM_VALUE) 
{ 
    // ... 
} 

Esa es una prueba de alcance "inclusivo". Debería ser fácil descubrir cómo hacer un control "exclusivo".

No hay una función incorporada, pero tampoco hay manera de hacerlo que sea más eficiente que dos condiciones en cualquier arquitectura con la que estoy familiarizado. Cualquier función o macro finalmente se reducirá a lo mismo que arriba.

Si le preocupa que sea lento, entonces no. Solo preocúpate por el rendimiento si realmente ves que esto es, de alguna manera, un cuello de botella. La optimización prematura no vale su tiempo.

+0

+1 para "optimización prematura no vale la pena su tiempo" – aslisabanci

+0

Estaba buscando algo como 'if (x en rango) {}' donde "rango" es algún tipo de estructura que permite que la instrucción devuelva SÍ si el valor está entre range.startInterval y range.endInterval, por ejemplo. No sé si existe tal cosa, pero creo que vale la pena preguntar :) –

+1

Podrías usar 'NSRange' y' NSLocationInRange() 'si realmente quisieras, pero al final del día, es solo envoltorios alrededor de un mayor que y menor que el cheque. No hay un operador 'in' integrado ni nada similar. –

0

Bueno, no creo que haya una función incorporada, pero podrías escribir la tuya en segundos.

simplemente

return (theInt >= min && theInt <= max); 
2

Añadir este método:

- (BOOL)float:(float)aFloat between:(float)minValue and:(float)maxValue { 
    if (aFloat >= minValue && aFloat <= maxValue) { 
     return YES; 
    } else { 
     return NO; 
    } 
} 

y utilizarlo como esto:

float myFloat = 3.45; 
if ([self float:myFloat between:3 and:4]) { 
    //Do something 
} 

Esta es una solución muy fácil.

+0

Bastará con escribir return (aFloat> = minValue && aFloat <= maxValue) sin el si -más. – taskinoor

+0

No sabía, que puedo hacer esto directamente. Gracias. –

0

Haciendo como tal será interpretado como: c> = a & & c < b

NSLocationInRange(c, NSMakeRange(a, (b - a)))

Si desea comparar la siguiente manera: c> = a & & c < = b que debe hacer así:

NSLocationInRange(c, NSMakeRange(a, (b - a) + 1))

NSRange es una estructura:

{ 
    location, // Starting point 
    length  // Length from starting point to end range 
} 

Así que si quiere un rango de 5 a 15 incluido -----> NSMakeRange (5, 11);

* Si te molesta un poco, solo cuenta con tu dedo del 5 al 15;).Así es como lo hago cuando llego a este punto de la noche cuando su difícil pensar: p

Si está trabajando con int firmado, le aconsejo que para crear una macro;)

#define MY_AWESOME_MACRO_COMPARE(c, a, b) ((c >= a) && (c <= b)) 

esperanza I ayudado :)

¡Salud!)!

0

En Objective-C puede utilizar esta sencilla prueba:

if (variable >= MINVALUE && variable <= MAXVALUE) { 
    NSLog(@" the number fits between two numbers"); 
} else { 
    NSLog(@" the number not fits between two numbers"); 
} 

BOOL FitsBetweenTwoNumber = NSLocationInRange(variable, NSMakeRange(MINVALUE, (MAXVALUE - MINVALUE))); 
if (FitsBetweenTwoNumber) { 
    NSLog(@" the number fits between two numbers"); 
} else { 
    NSLog(@" the number not fits between two numbers"); 
} 

puede utilizar NSPredicate para juzgar si una matriz es en el rango, si se utiliza CoreData me gusta:

NSManagedObjectContext *context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext]; 
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", MINVALUE, MAXVALUE]; 
NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
[request setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:context]]; 
[request setPredicate:predicate]; 

NSError *error = nil; 
NSArray *results = [context executeFetchRequest:request error:&error]; 

if (error == nil) { 
    if(results.count >0) { 
     NSLog(@" the number fits between two numbers"); 
    } else { 
     NSLog(@" the number not fits between two numbers"); 
    } 
} else if (error) { 
    NSLog(@"%@", error); 
} 

si no utiliza coreData, también puede usar NSPredicate:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)", MINVALUE, MAXVALUE]; 

NSArray *results = [@[@(variable)] filteredArrayUsingPredicate:predicate]; 
if(results.count >0) { 
    NSLog(@" the number fits between two numbers"); 
} else { 
    NSLog(@" the number not fits between two numbers"); 
} 
Cuestiones relacionadas