您好我正在制作一个从键盘输入的程序,我想知道是否有任何方法可以从键盘获取输入并将其存储在NSString
对象中。
答案 0 :(得分:6)
如果您是作为命令行应用程序执行此操作,那么我上周编写的代码是从命令提示符处获取一行(我将其设为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;
}
然后我会像这样使用它:
NSString * input = [NSString stringFromStandardInDelimitedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
它不能很好地处理unicode字符(尽管使用unichar),因为getchar()只返回一个常规字符。但是,对于基本的命令行文本输入,它工作得很好。但是,请注意这将阻止执行它的线程(因为getchar()是阻塞调用)。
答案 1 :(得分:3)
- (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;
}
答案 2 :(得分:1)
为什么不呢?
NSFileHandle *kbd = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [kbd availableData];
NSString *option = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];