How do I clear the console in Objective-C

MacOS

Question or issue on macOS:

I’m making a console-based application in Objective-C which relies on being able to clear the console periodically. How can this be done? All I’ve seen on SO and Google were ways to have the developer clear the console with X-Code, but that will not do.

One solution I found on Yahoo! Answers told me to do the following, but it does not run due to being unable to find a 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];

How to solve this problem?

Solution no. 1:

Try using :

system( "clear" );

Important headers :

#include 

Hint : Objective-C is still C, right?


UPDATE :


In case of a “TERM environment variable not set.” error :

1) Run the program, directly from your terminal (or just ignore the error while testing it in Xcode; it’s supposed to run in a normal terminal anyway, huh?)

2) Set the TERM variable in your Scheme’s settings.
To what? Just run this in your terminal to see what “TERM” should be :

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

enter image description here

Solution no. 2:

The way to do this without spawning a subprocess is to use ncurses.

#include 
#include 
#include 

int main(void)
{
    setupterm(NULL, STDOUT_FILENO, NULL);
    tputs(clear_screen, lines ? lines : 1, putchar);
}

Compile with -lncurses.

The setupterm() call only needs to be done once. After that, use the tputs() call to clear the screen.

Solution no. 3:

Why /bin/bash?

Just do:

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

Alternatively, using the C way:

#include 

...
system("/usr/bin/clear");
...

Solution no. 4:

You can use apple script

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

Use NSAppleScript class for executing applescript from obj-C program.

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 the key command for clear display, that will break script.

Hope this helps!