iOS開發,ios開發吧
前言:實際開發,我們可能會有這樣的需求,就是為檔案添加自訂的屬性,或者是可以將檔案的相關資訊添加進該檔案的屬性中,這樣可以以備下次讀取利用。
那麼本文就是要介紹"拓展檔案屬性的工具類"
github網址也給出了這個工具類的樣本源碼:https://github.com/HeYang123456789/NSURLSession-ExpendedAttributesTool
這個工具類的設計學習來源來自老譚部落格筆記:http://www.tanhao.me/pieces/1102.html/ 老譚講解了兩種方法為本地檔案屬性列表添加屬性,其中用方法二(通過NSFileManager一個特殊的AttributeName)我發現好像無效了,暫時不明原因,待以後再探究和解決。但是方法一是有效,代碼就無比雞賊的拷貝展示如下嘍:
ExpendFileAttributes.h
1 // 2 // ExpendFileAttributes.h 3 // NSURLSession實現離線斷點續傳 4 // 5 // Created by HEYANG on 16/2/19. 6 // Copyright © 2016年 HEYANG. All rights reserved. 7 // 8 9 /**10 * ExpendFileAttributes工具類下載源碼:https://github.com/HeYang123456789/NSURLSession-ExpendedAttributesTool11 */12 13 #import <Foundation/Foundation.h>14 15 @interface ExpendFileAttributes : NSObject16 17 /** 為檔案增加一個擴充屬性,值是字串 */18 + (BOOL)extendedStringValueWithPath:(NSString *)path key:(NSString *)key value:(NSString *)value;19 20 /** 讀取檔案擴充屬性,值是字串 */21 + (NSString *)stringValueWithPath:(NSString *)path key:(NSString *)key;22 23 24 @end
ExpendFileAttributes.m
1 // 2 // ExpendFileAttributes.m 3 // NSURLSession實現離線斷點續傳 4 // 5 // Created by HEYANG on 16/2/19. 6 // Copyright © 2016年 HEYANG. All rights reserved. 7 // 8 9 /**10 * ExpendFileAttributes工具類下載源碼:https://github.com/HeYang123456789/NSURLSession-ExpendedAttributesTool11 */12 13 #import "ExpendFileAttributes.h"14 15 #include <sys/xattr.h>16 17 @implementation ExpendFileAttributes18 //為檔案增加一個擴充屬性19 + (BOOL)extendedStringValueWithPath:(NSString *)path key:(NSString *)key value:(NSString *)stringValue20 {21 NSData* value = [stringValue dataUsingEncoding:NSUTF8StringEncoding];22 ssize_t writelen = setxattr([path fileSystemRepresentation],23 [key UTF8String],24 [value bytes],25 [value length],26 0,27 0);28 return writelen==0?YES:NO;29 }30 //讀取檔案擴充屬性31 + (NSString *)stringValueWithPath:(NSString *)path key:(NSString *)key32 {33 ssize_t readlen = 1024;34 do {35 char buffer[readlen];36 bzero(buffer, sizeof(buffer));37 size_t leng = sizeof(buffer);38 readlen = getxattr([path fileSystemRepresentation],39 [key UTF8String],40 buffer,41 leng,42 0,43 0);44 if (readlen < 0){45 return nil;46 }47 else if (readlen > sizeof(buffer)) {48 continue;49 }else{50 NSData *data = [NSData dataWithBytes:buffer length:readlen];51 NSString* result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];52 NSLog(@"result---%@",result);53 return result;54 }55 } while (YES);56 return nil;57 }58 @end
列印展示結果: