How to clear the console in Objective-C

I am making a console application in Objective-C that relies on the ability to clean up the console periodically. How can this be done? All I've seen on SO and Google are ways for the developer to clear the console using X-Code, but that won't be.

One solution I found on Yahoo! The answers told me to do the following, but it does not start due to the inability to find the file:

NSTask *task; task = [[NSTask alloc]init]; [task setLaunchPath: @"/bin/bash"]; NSArray *arguments; arguments = [NSArray arrayWithObjects: @"clear", nil]; [task setArguments: arguments]; [task launch]; [task waitUntilExit]; 
+7
source share
4 answers

Try using:

 system( "clear" ); 

Important headings:

 #include <stdlib.h> 

Hint: Objective-C is still C, right?


UPDATE:


In case the environment variable "TERM is not set." :

1) Run the program directly from your terminal (or just ignore the error when testing it in Xcode, it should work in a regular terminal, right?)

2) Set the TERM variable in the schema settings. To what? Just run this in your terminal to find out what should be "TERM":

 DrKameleons-MacBook-Pro:Documents drkameleon$ echo $TERM xterm-256color 

enter image description here

+6
source

A way to do this without creating a subprocess is to use ncurses.

 #include <curses.h> #include <term.h> #include <unistd.h> int main(void) { setupterm(NULL, STDOUT_FILENO, NULL); tputs(clear_screen, lines ? lines : 1, putchar); } 

Compile with -lncurses .

The setupterm() call is required only once. After that, use the tputs() call to clear the screen.

+4
source

Why /bin/bash ?

Just do:

 NSTask *task = [NSTask launchedTaskWithLaunchPath:@"/usr/bin/clear" arguments:[NSArray array]]; 

Alternatively, using method C:

 #include <stdlib.h> ... system("/usr/bin/clear"); ... 
+3
source

You can use apple script

 tell application "Console" activate tell application "System Events" keystroke "k" using command down end tell end tell 

Use the NSAppleScript class to execute applescript from obj-C.

 NSAppleScript *lClearDisplay = [[NSAppleScript alloc] initWithSource:@"tell application \"Console\"\n \ activate\n \ tell application \"System Events\"\n \ keystroke \"k\" using command down\n \ end tell\n \ end tell "]; NSDictionary *errorInfo; [lClearDisplay executeAndReturnError:&errorInfo]; 

Note:
If Apple changes or removes ⌘k as a key command for a clear display, this will break the script.

+1
source

All Articles