How can I execute a terminal command (like grep
) from my Objective-C Cocoa application?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- back button text does not change
- iOS (objective-c) compression_decode_buffer() retu
- how to find the index position of the ARRAY Where
相关文章
- 现在使用swift开发ios应用好还是swift?
- Visual Studio Code, MAC OS X, OmniSharp server is
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- IntelliJ IDEA can't open projects or add SDK o
- Automator: How do I use the Choose from List actio
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
There is also good old POSIX system("echo -en '\007'");
Custos Mortem said:
For blocking/non-blocking call issues regarding
NSTask
read below:Source code of asynctask.m is available at GitHub.
Here's how to do it in Swift
This is based on inkit's Objective-C answer above. He wrote it as a category on
NSString
— For Swift, it becomes an extension ofString
.extension String.runAsCommand() -> String
Usage:
or just:
Example:
Note the
Process
result as read from thePipe
is anNSString
object. It might be an error string and it can also be an empty string, but it should always be anNSString
.So, as long as it's not nil, the result can cast as a Swift
String
and returned.If for some reason no
NSString
at all can be initialized from the file data, the function returns an error message. The function could have been written to return an optionalString?
, but that would be awkward to use and wouldn't serve a useful purpose because it's so unlikely for this to occur.I wrote this "C" function, because
NSTask
is obnoxious..oh, and for the sake of being complete / unambiguous…
Years later,
C
is still a bewildering mess, to me.. and with little faith in my ability to correct my gross shortcomings above - the only olive branch I offer is a rezhuzhed version of @inket's answer that is barest of bones, for my fellow purists / verbosity-haters...Or since Objective C is just C with some OO layer on top you can use the posix conterparts:
They are included from unistd.h header file.
Objective-C (see below for Swift)
Cleaned up the code in the top answer to make it more readable, less redundant, added the benefits of the one-line method and made into an NSString category
Implementation:
Usage:
And if you're having problems with output encoding:
Hope it's as useful to you as it will be to future me. (Hi, you!)
Swift 4
Here's a Swift example making use of
Pipe
,Process
, andString
Usage: