How can I add OS X “tags” to files programmatically?

前端 未结 9 1487
轻奢々
轻奢々 2021-01-29 22:23

Since Mavericks, OS X has had the ability to tag & colour files in Finder.

\"finder

Is there any

9条回答
  •  醉酒成梦
    2021-01-29 22:45

    Starting with Mavericks, it is possible to get and set color tags in Cocoa, using NSURL.

    NSURL has a slew of properties that can be set or read, through the respective setResourceValue:forKey:error: and getResourceValue:forKey:error: methods.

    Using the NSURLLabelNumberKey key, you can set the color tags, as follows:

    NSURL *fileURL = [NSURL fileURLWithPath:@"/Users/[username]/Documents/[some_file]"];
    NSError *resourceError;
    if (![fileURL setResourceValue:@(2) forKey:NSURLLabelNumberKey error:&resourceError]) {
        NSLog(@"Error while setting file resource: %@", [resourceError localizedDescription]);
    }
    

    If this is executed on a file that only has one color, then it clears the current color, and sets the specified color. However, if multiple colors are already set on the file, then it does not clear the existing colors before setting the specified color.

    Here is the value-color mapping (on El Capitan):

    • @(0): None
    • @(1): Grey
    • @(2): Green
    • @(3): Purple
    • @(4): Blue
    • @(5): Yellow
    • @(6): Red
    • @(7): Orange

    I have not been able to set a tag using NSURLLabelColorKey. Here is my experience on El Capitan, with the keys related to 'tags' (Colors):

    • NSURLLabelNumberKey: can be read/set successfully, with numbers 0-7. Any other number will return an error. If there are multiple tags set, then this will return the index of the first color that is set, as it searches numerically through the indexes 1 through 7. Although you can clear a color in Finder by clicking on the color, programmatically setting a color that is already set does not clear that color.
    • NSURLLabelColorKey: returns nil, even when a color tag is set for a file. Setting a value with this key has no effect.
    • NSURLTagNamesKey: returns an array of the color names for the tags that are set.

提交回复
热议问题