This is how you can add command line interface to youx XCode command line app.
Add a new Objective-C file
Rename the Objective-C file extension to .mm
Add a new header file
Copy in the following code to the header file
IOHelper.h
#import <Foundation/Foundation.h> @interface IOHelper : NSObject - (NSString *)readLine; - (void)outputLine:(NSString *)line; @end
Copy in the following code to the .mm file
IOHelper.mm
#import "IOHelper.h" #include <string> #include <iostream> @implementation IOHelper - (NSString *)readLine { std::string input; getline(std::cin, input); return [NSString stringWithCString:input.c_str() encoding:[NSString defaultCStringEncoding]]; } - (void)outputLine:(NSString *)line { std::string outputLine([line cStringUsingEncoding:[NSString defaultCStringEncoding]]); std::cout << outputLine << std::endl; } @end
Copy in the following code to the main.m file
main.m
#import <Foundation/Foundation.h> #import "IOHelper.h" int main(int argc, const char * argv[]) { @autoreleasepool { IOHelper *io = [IOHelper new]; [io outputLine:@"Hi! Welcome to XpStuff 2014-06-12."]; [io outputLine:@"Who are you?"]; NSString *name = [io readLine]; [io outputLine:[NSString stringWithFormat:@"OK %@, go build a game!", name]]; } return 0; }
Run (Command + R). Should see the following in the console (Command + Shift + Y).
Leave a Reply