【发布时间】:2017-07-20 02:44:28
【问题描述】:
我有一个程序应该使用FileMerge 比较两个文件。
这确实有效,但偶尔会失败。我怀疑这是作为参数传递的路径包含空格字符的时候。
以下代码片段构建任务并启动它。
NSTask *task = [[NSTask alloc] init];
NSPipe *pipe = [NSPipe pipe];
[task setStandardOutput: pipe];
[task setStandardInput:[NSPipe pipe]]; //The magic line that keeps your log where it belongs
NSFileHandle *file = [pipe fileHandleForReading];
[task setLaunchPath: @"/bin/sh"];
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[[NSUserDefaults standardUserDefaults] stringForKey:PREF_COMPARE_COMMAND],
@"Compare", // $0 place holder
source,
target,
nil];
[task setArguments:arguments];
[task setEnvironment:[NSDictionary dictionaryWithObject:@"/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin" forKey:@"PATH"]];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(pipeReadCompletionNotification:)
name:NSFileHandleReadCompletionNotification
object:file];
[file readInBackgroundAndNotify];
[task launch];
我尝试了许多选项来尝试转义空格或将路径括在引号中,但均未成功。我欢迎任何建议。
作为运行结果的典型参数是:-
"-c",
"opendiff $1 $2",
Compare,
"/Users/ian/temp/Indian Pacific/RailRes Travel Documentation1.pdf",
"/Users/ian/temp/Indian Pacific/RailRes Travel Documentation.pdf"
我试过了
[source stringByReplacingOccurrencesOfString:@" " withString:@"\\ "],
[source stringByReplacingOccurrencesOfString:@" " withString:@"\ "],
第一个实际插入\\ 第二个产生编译错误unknown escape sequence
我尝试了 Ken Thomases 的建议(知道我的名字没有')
[[@"'" stringByAppendingString:source] stringByAppendingString:@"'"],
[[@"'" stringByAppendingString:target] stringByAppendingString:@"'"],
不幸的是,这导致了争论
"-c",
"opendiff $1 $2",
Compare,
"'/Users/ian/temp/Indian Pacific/RailRes Travel Documentation1.pdf'",
"'/Users/ian/temp/Indian Pacific/RailRes Travel Documentation.pdf'"
并以同样的方式失败。 /Users/ian/temp/Indian does not exist
编辑 _______________________ 工作代码 _____________________________________
NSArray *arguments = [NSArray arrayWithObjects:
@"-c" ,
[NSString stringWithFormat:@"%@ '%@' '%@'", @"opendiff", source, target],
nil];
【问题讨论】:
-
你试过用“\”替换“”吗?
标签: objective-c macros