Search code examples
objective-cnsfilemanagernstask

Objective-C, NSTask won't touch files


I have the following code (below) in my app, which simply tries to use NSTask to touch one file with the directory time/date stamp. It works just fine in an app which only accesses one directory all the time, however, it doesn't with another that frequently changes directories to access some of it's data. When I check the currentfile and currentpath they both show the correct paths. I've expired every possibility I can think of; any help would be great appreciated — thank you.

- (void)someMethod:(NSString *)currentfile {

    NSFileManager *filemanager = [[NSFileManager alloc] init];

    if ([filemanager changeCurrentDirectoryPath: @"/"] == NO)
    NSLog (@"Cannot change directory.\n");

    NSString *currentpath = [filemanager currentDirectoryPath];
    NSLog (@"Current directory is %@", currentpath);

    [filemanager release];

    NSArray*arguments = [NSArray arrayWithObjects:@"-r",currentpath,currentfile,nil];

    [self touchFiles:arguments];

    return;
}

- (void)touchFiles:(NSArray *)arguments {

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

    [task setLaunchPath:@"/usr/bin/touch"];

    [task setArguments:arguments];

    [task launch];

    [task release];

    return;
}

Solution

  • You can change a file's modification time without using NSTask. Use -[NSURL setResourceValue:forKey:error:] with the key NSURLContentModificationDateKey.

    As to why your use of NSTask and touch is failing, perhaps you don't have permissions to modify the file's modification time. Check the console log to see if any error was reported from touch or redirect the task's standard error output to someplace else and check that.