您的位置:首页 > 编程语言

Xcode中如何通过代码运行命令行工具

2014-07-30 13:09 996 查看
// Run a command
+(NSString*)runCommand:(NSString*)cmd {

// Create an empty string

NSMutableString* mutableString = [NSMutableString
stringWithCapacity:0];

// Create a thread pool

NSAutoreleasePool *threadPool = [[NSAutoreleasePool
alloc]
init];

// Create a new task

NSTask *task = [[NSTask
alloc] init];

// Configure the task

[task setStandardOutput: [NSPipe
pipe]];

[task setStandardError: [task
standardOutput]];
[task
setLaunchPath:cmd];

// Launch the task
[task
launch];

// Append the output
NSData *data;

while ((data = [[[task
standardOutput] fileHandleForReading]
availableData]) && [data length]) {

NSString* output = [[[NSString
alloc] initWithData:data
encoding:NSASCIIStringEncoding]
autorelease];
[mutableString
appendString:output];
}

// Make sure the task is finished
[task
terminate];

// Release the thread pool
[threadPool
release];

// Return the output
return mutableString;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: