Storing arbitrary metadata with a plain-text file
cocoa, objective-c
Solution
Use extended attributes. See setxattr().
Here's a sample call to write a string:
NSData* encodedString = [theString dataUsingEncoding:NSUTF8StringEncoding];
int rc = setxattr("/path/to/your/file", "com.yourcompany.yourapp.yourattributename", [encodedString bytes], [encodedString length], 0, 0);
if (rc)
/* handle error */;
To read a string:
ssize_t len = getxattr("/path/to/your/file", "com.yourcompany.yourapp.yourattributename", NULL, 0, 0, 0);
if (len < 0)
/* handle error */;
NSMutableData* data = [NSMutableData dataWithLength:len];
len = getxattr("/path/to/your/file", "com.yourcompany.yourapp.yourattributename", [data mutableBytes], len, 0, 0);
NSString* string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
PS: Don't you have to set the bounty on the question before it's answered?
Problem
I am writing a text-editor and I would need to store a few pieces of information (generally just a few strings; the storage needn't be particularly durable) with each file the app saves (without that being part of the text-file as other apps might read it and the info is only specific to my app). How would I go about this? More info: I have a NSDocument set up and I would like to simply store a NSString instance variable as a per file meta-datum. Based on the answers below I've come up with this, which is currently buggy and causes the program to crash on startup: ``` #import <sys/xattr.h> @interface MyDocument : NSDocument { NSString *metadatum; } @implementation MyDocument - (BOOL)writeToURL:(NSURL *)url ofType:(NSString *)type error:(NSError **)err { BOOL output = [super writeToURL:url ofType:type error:err]; if(!setxattr([[url path] cStringUsingEncoding:NSUTF8StringEncoding], "eu.gampleman.xattrs.style", [metadatum cStringUsingEncoding:NSUTF8StringEncoding], sizeof(char) * [styleName length], 0, 0)) { NSLog(@"Write failure"); } return output; } - (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)type error:(NSError **)err { char *output; ssize_t bytes = getxattr([[url path] cStringUsingEncoding:NSUTF8StringEncoding], "eu.gampleman.xattrs.style", &output, 1024, 0, 0); if (bytes > 0) { metadatum = [[NSString alloc] initWithBytes:output length:bytes encoding:NSUTF8StringEncoding]; // <- crashes here with "EXC_BAD_ACCESS" } return [super readFromURL:url ofType:type error: err]; } // ... // fairly standard -dataOfType:error: and // -readFromData:ofType:error: implementations ``` PS: If your answer is really good (with sample code, etc.), I will award a 100rep bounty.