Cómo leer la entrada desde el teclado en Objective-C
-
08-07-2019 - |
Pregunta
Hola, estoy haciendo un programa que recibe información del teclado y me preguntaba si había alguna forma de obtener información del teclado y almacenarla en un objeto NSString
.
Solución
Si está haciendo esto como una aplicación de línea de comandos, aquí está el código que escribí la semana pasada para obtener una línea desde el símbolo del sistema (lo convertí en una categoría NSString
):
+ (NSString *) stringFromStandardInDelimitedByCharactersInSet:(NSCharacterSet *)delimiters {
NSMutableString * string = [NSMutableString string];
unichar input = '\0';
while (input = getchar()) {
if ([delimiters characterIsMember:input]) { break; }
[string appendFormat:@"%C", input];
}
return string;
}
Y luego lo usaría así:
NSString * input = [NSString stringFromStandardInDelimitedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
No maneja muy bien los caracteres unicode (a pesar de usar unichar), porque getchar () solo devuelve un carácter normal. Sin embargo, para la entrada de texto de línea de comandos básica, funciona bastante bien. Sin embargo, tenga en cuenta que esto bloqueará el hilo en el que se ejecuta (ya que getchar () es una llamada de bloqueo).
Otros consejos
- (id)init {
if( !(self = [super init]) ){
return nil;
}
void (^monitorHandler)(NSEvent *);
monitorHandler = ^(NSEvent *theEvent){
switch ([theEvent keyCode]) {
case 123: // Left arrow
NSLog(@"Left behind.");
break;
case 124: // Right arrow
NSLog(@"Right as always!");
break;
case 125: // Down arrow
NSLog(@"Downward is Heavenward");
break;
case 126: // Up arrow
NSLog(@"Up, up, and away!");
break;
default:
break;
}
};
// Creates an object we do not own, but must keep track
// of so that it can be "removed" when we're done
[NSEvent addGlobalMonitorForEventsMatchingMask:(NSKeyDownMask) handler:monitorHandler];
return self;
}
¿Por qué no esto?
NSFileHandle *kbd = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [kbd availableData];
NSString *option = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];