以前开发的时候想要给文件添加一个属性,系统提供的属性不太够, 想增加新的额外属性 . 当时没找到,今天偶然看见了,感激并记录下.
http://www.tanhao.me/pieces/1102.html/
http://www.cnblogs.com/goodboy-heyang/p/5201322.html
每一个文件都有一组属性信息,我们通常可以用以下几种方法来获得属性信息:
NSString *path = @"...";
//通过NSFileManager获取文件的属性
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:NULL];
NSLog(@"%@",attributes);
//通过MDItem获取文件的属性
MDItemRef item = MDItemCreate(kCFAllocatorDefault, (__bridge CFStringRef)path);
CFArrayRef names = MDItemCopyAttributeNames(item);
attributes = (__bridge_transfer NSDictionary *)(MDItemCopyAttributes(item, names));
CFRelease(item);
NSLog(@"%@",attributes);
//通过NSURL获取文件属性
NSURL *fileUrl = [NSURL fileURLWithPath:path];
attributes = [fileUrl resourceValuesForKeys:[NSArray arrayWithObject:NSURLFileSizeKey] error:NULL];
NSLog(@"%@",attributes);
但如果我们需要把自定义的一些数据写入到属性中怎么办呢(比如Safari下载文件之后会将文件的来源信息写入到属性中)?下面就通过两种不同的方式来实现:
方法一(通过定义在sys/xattr.h的函数实现):
#include <sys/xattr.h>
//为文件增加一个扩展属性
- (BOOL)extended1WithPath:(NSString *)path key:(NSString *)key value:(NSData *)value
{
ssize_t writelen = setxattr([path fileSystemRepresentation],
[key UTF8String],
[value bytes],
[value length],
0,
0);
return writelen==0?YES:NO;
}
//读取文件扩展属性
- (NSData *)extended1WithPath:(NSString *)path key:(NSString *)key
{
ssize_t readlen = 1024;
do {
char buffer[readlen];
bzero(buffer, sizeof(buffer));
size_t leng = sizeof(buffer);
readlen = getxattr([path fileSystemRepresentation],
[key UTF8String],
buffer,
leng,
0,
0);
if (readlen < 0){
return nil;
}
else if (readlen > sizeof(buffer)) {
continue;
}else{
NSData *result = [NSData dataWithBytes:buffer length:readlen];
return result;
}
} while (YES);
return nil;
}
方法二(通过NSFileManager一个特殊的AttributeName):
//为文件增加一个扩展属性
- (BOOL)extended2WithPath:(NSString *)path key:(NSString *)key value:(NSData *)value
{
NSDictionary *extendedAttributes = [NSDictionary dictionaryWithObject:
[NSDictionary dictionaryWithObject:value forKey:key]
forKey:@"NSFileExtendedAttributes"];
NSError *error = NULL;
BOOL sucess = [[NSFileManager defaultManager] setAttributes:extendedAttributes
ofItemAtPath:path error:&error];
return sucess;
}
//读取文件扩展属性
- (NSData *)extended2WithPath:(NSString *)path key:(NSString *)key
{
NSError *error = NULL;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&error];
if (!attributes) {
return nil;
}
NSDictionary *extendedAttributes = [attributes objectForKey:@"NSFileExtendedAttributes"];
if (!extendedAttributes) {
return nil;
}
return [extendedAttributes objectForKey:key];
}