Created
February 25, 2014 15:36
-
-
Save jxpx777/9211303 to your computer and use it in GitHub Desktop.
A demonstration of how to read and set tags using xattr APIs.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (NSSet *)tagsForFileAtPath:(NSString *)path { | |
const char *attrName = [@"com.apple.metadata:_kMDItemUserTags" UTF8String]; | |
const char *filePath = [path fileSystemRepresentation]; | |
ssize_t bufferLength = getxattr(filePath, attrName, NULL, 0, 0, 0); | |
void *buffer = malloc(bufferLength); | |
// now actually get the attribute string | |
getxattr(filePath, attrName, buffer, 255, 0, 0); | |
// convert to NSString | |
NSData *tagsData = [NSData dataWithBytes:buffer length:(NSUInteger)bufferLength]; | |
free(buffer); | |
NSArray *tags = [NSPropertyListSerialization propertyListWithData:tagsData options:NSPropertyListImmutable format:NULL error:nil]; | |
return [NSSet setWithArray:tags]; | |
} | |
- (void)setTags:(NSSet *)newTags forFileAtPath:(NSString *)path{ | |
const char *attrName = [@"com.apple.metadata:_kMDItemUserTags" UTF8String]; | |
const char *filePath = [path fileSystemRepresentation]; | |
NSData *tagData = [NSPropertyListSerialization dataWithPropertyList:[newTags allObjects] format:NSPropertyListBinaryFormat_v1_0 options:0 error:nil]; | |
setxattr(filePath, attrName, [tagData bytes], [tagData length], 0, 0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment