Unix System Call in Objective-C
Is it possible to make system call in Objective-C?
I have the following code:
if (!system("ls -l")) {
NSLog(@"Successfully executed");
} else {
NSLog(@"Error while 开发者_如何学运维executing the command");
}
How to get the output?
Thanks
This is a perfect candidate for using -[NSFileManager contentsOfDirectoryAtPath:error:]
instead of wrapping a built-in shell function and parsing the output. For general-purpose commands where you need the output — and where there is no equivalent functionality "for free" in Cocoa (it just takes time to learn the available APIs) — NSTask is generally a far better alternative than system()
.
You should use NSTask. If you just need the results of ls
, there are more appropriate filesystem wrappers in Cocoa.
If you like to do it the C way you can use popen
. This can be used to read the output also. But the answers about using Objective-C solutions are probably the better ones.
Objective-C does not prevent a program to invoque system()
or any of its equivalents.
CocoaTouch does.
精彩评论