请运行此演示,看看它是否与您尝试做的类似。该代码将允许您通过单击按钮在应用程序的终端窗口中运行 NSTask。将以下代码保存在名为“runCmd.m”的文件中,然后使用下面给出的说明从命令行编译:
/*
Run from Terminal using: clang runCmd.m -fobjc-arc -framework Cocoa -o runCmd && ./runCmd
Should print current calendar when 'RunCommand' button is hit.
*/
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate> {
NSWindow *window;
}
-(void) runMyCmd;
-(void) buildMenu;
-(void) buildWindow;
@end
@implementation AppDelegate
- (void) runMyCmd {
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/sh"];
NSArray *args = [NSArray arrayWithObjects: @"-c", @"cal", nil];
[task setArguments: args];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
[task launch];
[task waitUntilExit];
NSData *data = [[pipe fileHandleForReading] readDataToEndOfFile];
NSString *string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog (@"\n%@",string);
}
- (void) buildMenu {
NSMenu *menubar = [NSMenu new];
NSMenuItem *menuBarItem = [NSMenuItem new];
[menubar addItem:menuBarItem];
[NSApp setMainMenu:menubar];
NSMenu *appMenu = [NSMenu new];
NSMenuItem *quitMenuItem = [[NSMenuItem alloc] initWithTitle:@"Quit"
action:@selector(terminate:) keyEquivalent:@"q"];
[appMenu addItem:quitMenuItem];
[menuBarItem setSubmenu:appMenu];
}
- (void) buildWindow {
#define _wndW 200
#define _wndH 150
window = [[NSWindow alloc] initWithContentRect: NSMakeRect( 0, 0, _wndW, _wndH )
styleMask: NSWindowStyleMaskTitled | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable
backing: NSBackingStoreBuffered defer: NO];
[window center];
[window setTitle: @"Test window"];
[window makeKeyAndOrderFront: nil];
// **** RunCmdButton **** //
NSButton *runBtn =[[NSButton alloc]initWithFrame:NSMakeRect( 30, 60, 135, 30 )];
[runBtn setBezelStyle:NSBezelStyleRounded ];
[runBtn setTitle: @"RunCommand"];
[runBtn setAction: @selector(runMyCmd)];
[[window contentView] addSubview: runBtn];
// **** Quit btn **** //
NSButton *quitBtn = [[NSButton alloc]initWithFrame:NSMakeRect( _wndW - 50, 5, 40, 40 )];
[quitBtn setBezelStyle:NSBezelStyleCircular ];
[quitBtn setTitle: @"Q" ];
[quitBtn setAutoresizingMask: NSViewMinXMargin];
[quitBtn setAction:@selector(terminate:)];
[[window contentView] addSubview: quitBtn];
}
- (void) applicationWillFinishLaunching: (NSNotification *)notification {
[self buildMenu];
[self buildWindow];
}
- (void) applicationDidFinishLaunching: (NSNotification *)notification {
}
@end
int main () {
NSApplication *application = [NSApplication sharedApplication];
AppDelegate *appDelegate = [[AppDelegate alloc] init];
[application setDelegate:appDelegate];
[application run];
return 0;
}