本文将用一个例子帮助你理解如何使用NSTask,例子通过在Cocoa中执行一个perl脚本,实现去掉给定NSString中的所有HTML标签。

?

这里是一个简单的 perl 脚本,文件名是 stripper.pl ,功能是去掉所有 HTML 标签。
?
#!/usr/bin/perl
while (<>) {
??? $_ =~ s/<[^>]*>//gs;
print $_;
}
?
记得把这个脚本 chmod +x ,将它加入项目中,即得把它复制进执行文件包内。
?
这个方法会将 string 参数直接传递给 perl 脚本,并将结果返回。
?
- (NSString *) stringStrippedOfTags: (NSString *) string
{
??? NSBundle *bundle = [NSBundle mainBundle];
??? NSString *stripperPath;
??? stripperPath = [bundle pathForAuxiliaryExecutable: @"stripper.pl"];
???????????
??? NSTask *task = [[NSTask alloc] init];
??? [task setLaunchPath: stripperPath];
???????????
??? NSPipe *readPipe = [NSPipe pipe];
??? NSFileHandle *readHandle = [readPipe fileHandleForReading];
???????????
??? NSPipe *writePipe = [NSPipe pipe];
??? NSFileHandle *writeHandle = [writePipe fileHandleForWriting];
???????????
??? [task setStandardInput: writePipe];
??? [task setStandardOutput: readPipe];
???????????
??? [task launch];
???????????
??? [writeHandle writeData: [string dataUsingEncoding: NSASCIIStringEncoding]];
??? [writeHandle closeFile];
???????????
??? NSMutableData *data = [[NSMutableData alloc] init];
??? NSData *readData;
???????????
??? while ((readData = [readHandle availableData])
???????? ??&& [readData length]) {
??????? [data appendData: readData];
??? }
???????????
??? NSString *strippedString;
??? strippedString = [[NSString alloc]
?????????????????????????????????????????????? ?initWithData: data
?????????????????????????????????????????????? ?encoding: NSASCIIStringEncoding];
???????????
??? [task release];
??? [data release];
??? [strippedString autorelease];
???????????
??? return (strippedString);
???????????
}