xattr への任意の文字列の読み取り/書き込みを可能にする Cocoanetics/DTFoundation を見つけました。
#import "Note+ExtendedAttribute.h"
#include <sys/xattr.h>
@implementation MyFile (ExtendedAttribute)
-(NSString*)dictionaryKey
{
return @"mydictionary";
}
-(BOOL)writeExtendedAttributeDictionary:(NSDictionary*)dictionary
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
options:0
error:&error];
if (! jsonData) {
return NO;
}
NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
const char *filepath = [[self filepath] fileSystemRepresentation];
const char *key = [[self dictionaryKey] UTF8String];
const char *value = [jsonString UTF8String];
int result = setxattr(filepath, key, value, strlen(value), 0, 0);
if(result != 0)
{
return NO;
}
return YES;
}
読む:
-(NSMutableDictionary*)readExtendedAttributeDictionary
{
const char *attrName = [[self dictionaryKey] UTF8String];
const char *filePath = [[self filepath] fileSystemRepresentation];
// get size of needed buffer
int bufferLength = getxattr(filePath, attrName, NULL, 0, 0, 0);
if(bufferLength<=0)
{
return nil;
}
// make a buffer of sufficient length
char *buffer = malloc(bufferLength);
// now actually get the attribute string
getxattr(filePath, attrName, buffer, bufferLength, 0, 0);
// convert to NSString
NSString *retString = [[NSString alloc] initWithBytes:buffer length:bufferLength encoding:NSUTF8StringEncoding];
// release buffer
free(buffer);
NSData *data = [retString dataUsingEncoding:NSUTF8StringEncoding];
if(data == nil || data.length == 0)
{
return nil;
}
NSError *error = nil;
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
if([json isKindOfClass:[NSDictionary class]])
{
return [NSMutableDictionary dictionaryWithDictionary:json];
}
if(error)
{
return nil;
}
return json;
}