Skip to content

Instantly share code, notes, and snippets.

@jxpx777
Created February 25, 2014 15:36
Show Gist options
  • Save jxpx777/9211303 to your computer and use it in GitHub Desktop.
Save jxpx777/9211303 to your computer and use it in GitHub Desktop.
A demonstration of how to read and set tags using xattr APIs.
- (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