Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

This is a cocoa app that adds a right click menu option to change whether a file is executable. It works by executing the system command chmod on each of the files. But I want to know if there is a better way to change the permission of a file, such as a cocoa function that can change the permission of a file.

What are some other ways that I can improve my code?

#import "AppDelegate.h"

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    // Insert code here to initialize your application
    [NSApp setServicesProvider:self];
    NSUpdateDynamicServices();
}
void runSystemCommand(NSString *cmd)
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/chmod"];
    if ([[NSFileManager defaultManager] isExecutableFileAtPath:cmd]) {
        //NSLog(@"is executable \n");
        [task setArguments:@[ @"-x", cmd]];
        [task launch];

    } else {
        //NSLog(@"is not executable \n");
        [task setArguments:@[ @"+x", cmd]];
        [task launch];

    }
}
- (void)handleServices:(NSPasteboard *)pboard
              userData:(NSString *)userData
                 error:(NSString **)error {
    if([[pboard types] containsObject:NSFilenamesPboardType]){
        NSArray* fileArray=[pboard propertyListForType:NSFilenamesPboardType];
        int i;
        int count;
        count = [fileArray count];
        for (i = 0; i < count; i++){
            //NSLog (@"%@", [fileArray objectAtIndex: i]);
            runSystemCommand([fileArray objectAtIndex: i]);
        }
    }
}

@end

Here is the repository for the complete project.

share|improve this question

1 Answer 1

up vote 3 down vote accepted

The relevant NSFileManager call, in Foundation, is - setAttributes:ofItemAtPath:error:, and it is the same in iOS as in Mac OS X. (It's funny that you already call - isExecutableFileAtPath: in the same NSFileManager class.) Even if you weren't familiar with Foundation, you would still be better off calling the POSIX function chmod(2) rather than the chmod(1) command.

You've neglected to do any kind of error handling on the /bin/chmod task. The operation could easily fail if, for example, the user did not have permission to modify the file.

It's misleading to name the parameter of runSystemCommand() cmd, as it really only contains the path to the file whose permissions are to be toggled.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.