加載plist或其它文件
獲取plist文件的路徑
NSString *path = [[NSBundle mainBundle] pathForResource:@"data.plist" ofType:nil];
// [NSBundle mainBundle] 表示獲取這個app安裝到手機上時的安裝目錄;然後在app的安裝根目錄下搜索data.plist文件的路徑;
NSString *path = NSHomeDirectory(); // 獲取沙盒地址
打開plist文件,獲取數據
NSArray *arr = [NSArray arrayWithContentsOfFile:path];
NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
通過xib動態創建UIView
XXView *view = [[[NSBundle mainBundle] loadNibNamed:@"TestXib" owner:nil options:nil] firstObject];
// NSBundle的loadNibNamed方法會返回一個UIView*的數組,因爲一個xib文件中可以添加多個UIView;
xib加載過程
<1>.根據文件名,搜索對應的xib(nib)文件;
<2>.加載xib文件的時候,會按順序加載xib文件中的每個控件;
<3>.對於每個控件,創建的時候都會查找對應的Class屬性中配置的類型,然後創建相應的類的對象;
<4>.創建好某個控件後,按照在xib中配置的屬性值,依次爲對象的屬性賦值;
創建好該控件的子控件,並設置屬性值,然後把該控件加入到父控件中;
最後返回一個數組,這個數組中包含創建的根元素對象;
加載xib的另外一種方法
UINib *nib = [UINib nibWithNIbName:@"" bundle:nil]; // 使用nainBundle,根據xib文件創建xib對象;
UIView *view = [[nib instantiateWithOwner:nil opsions:nil] lastObject]; // 獲取xib中某個對象(控件)
NSFileManager
NSFileManager *mgr = [NSFileManager defaultManager]; // 獲取文件操作對象;
// 在創建的時候,contents傳nil,此時文件大小爲0
[mgr createFileAtPath:filePath contents:nil attributes:nil];
[mgr fileExistsAtPath:]; // 文件是否存在;
// 獲取一個文件的屬性(大小,修改時間等);
NSDictionary *attr = [mgr attributesOfItemAtPath:file error:nil];// 獲取file路徑對應的文件信息(NSFileType,NSFileSize...)
[attr[NSFileSize] longLongValue]; // 獲取文件大小
[mgr removeItemAtPath:file error:nil]; // 刪除文件\文件夾
判斷file是否存在,並獲取是否是文件夾;
BOOL isDirectory = NO;
BOOL fileExists = [mgr fileExistsAtPath:file isDirectory:&isDirectory];
遍歷:
[mgr contentsOfDirectoryAtPath:file error:nil];
// 只能獲取file文件夾裏面的子文件\子文件夾;
[mgr subpathsAtPath:file] // 獲取file文件夾裏面的文件及子文件夾下面的文件;
NSFileHandle
讀寫文件句柄
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
handle.totalLength = 12; // 設置完整的文件長度;
[handle truncateFileAtOffset:length]; // 讓文件的長度爲length;
[handle seekToEndOfFile]; // 移動到文件的尾部;
[handle writeData:data]; // 從當前移動的位置寫入數據;
[handle closeFile]; // 關閉連接(不再輸入數據到文件中);
NSData
獲取本地文件二進制數據,兩種方式:
NSString *filepath = [[NSBundle mainBundle] pathForResource:@"xx.txt" ofType:nil];
NSData *data = [NSData dataWithContentsOfFile:filepath];
// 給本地文件發送一個請求;
NSURL *fileurl = [[NSBundle mainBundle] URLForResource:"xx.txt" withExtension:nil];
NSURLRequest *request = [NSURLRequest requestWithURL:fileurl];
NSURLResponse *response = nil;
NSData *d = [NSURLConnection sendSynchronousRequest:request returningResponse:response error:nil];
// response.MIMETYPE; // 文件類型;
NSData *data1 = [NSData dataWithContentsOfURL:fileurl];
NSDictionary與NSData互轉
把dict字典對象序列化成NSData二進制數據
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:dict];
將二進制數據轉換成字典
NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithData:data];