老谭笔记

为文件增加自定义的扩展属性

每一个文件都有一组属性信息,我们通常可以用以下几种方法来获得属性信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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的函数实现):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#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):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//为文件增加一个扩展属性
- (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];
}