使文件在Objective-C中可执行的最佳方法

使文件在Objective-C中可执行的最佳方法,objective-c,Objective C,我需要能够通过代码执行一个文件,这非常有效,但是为了确保它成功,我首先必须在文件上设置可执行位。我目前正在通过NSTask运行chmod+x,但这似乎很笨拙: NSString *script = @"/path/to/script.sh"; // At this point, we have already checked if script exists and has a shebang NSFileManager *fileManager = [NSFileManager default

我需要能够通过代码执行一个文件,这非常有效,但是为了确保它成功,我首先必须在文件上设置可执行位。我目前正在通过NSTask运行
chmod+x
,但这似乎很笨拙:

NSString *script = @"/path/to/script.sh";
// At this point, we have already checked if script exists and has a shebang
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager isExecutableFileAtPath:script]) {
    NSArray *chmodArguments = [NSArray arrayWithObjects:@"+x", script, nil];
    NSTask *chmod = [NSTask launchedTaskWithLaunchPath:@"/bin/chmod" arguments:chmodArguments];
    [chmod waitUntilExit];
}

有什么建议吗?我没有找到任何代码示例,唯一的其他选项似乎是NSFileManager的
setAttributes:OfiItemPath:error:
NSFilePosixPermissions
属性。如果需要,我将执行POSIX读写逻辑,但我想看看是否有更优雅的方法。

使用
-setAttributes:ofItemAtPath:error:
。有什么不优雅的地方吗

另一种可能是使用POSIX函数


您在问题中列出的解决方案非常昂贵-运行任务相当于在操作系统上创建新进程,这肯定比使用
NSFileManager
chmod(2)更昂贵

NSFileManager方法的不雅之处在于必须建立一个非常冗长的字典结构。POSIX方法将是:

#include <sys/types.h>
#include <sys/stat.h>

const char path[] = "hardcoded/path";

/* Get the current mode. */
struct stat buf;
int error = stat(path, &buf);
/* check and handle error */

/* Make the file user-executable. */
mode_t mode = buf.st_mode;
mode |= S_IXUSR;
error = chmod(path, mode);
/* check and handle error */
#包括
#包括
常量字符路径[]=“硬编码/路径”;
/*获取当前模式*/
结构统计buf;
int error=stat(路径和buf);
/*检查并处理错误*/
/*使文件用户可执行*/
mode_t mode=buf.st_mode;
模式|=S|uIXUSR;
错误=chmod(路径、模式);
/*检查并处理错误*/

-setAttributes:ofItemAtPath:error:
绝对是处理此问题的正确方法。请注意:由于字符串文字是常量,因此无需在第一行中使用
+[NSString stringWithString::
。是的,这不在我的实际代码中(包含此代码只是为了让脚本表示的内容更加清晰),但我把它改得更感性了。我同意,是字典让我的口味不好。我将尝试使用POSIX方法来提高速度,如果C代码对我影响太大,可能会切换到
setAttributes:ofItemAtPath:error:
。谢谢大家,谢谢你们的示例代码Jeremy!