應用沙盒
-
應用程序包:保存所有資源文件和可執(zhí)行文件
-
Documents:需要持久化的數(shù)據(jù)驱显,iTunes會同步。eg:游戲存檔
-
tmp:臨時數(shù)據(jù),應用不運行時系統(tǒng)也可能清除該目錄下文件徘公,iTunes不會同步
-
Library/Cache:需要持久化的文件,iTunes不會同步哮针。一般存儲體積大关面、不需要備份的非重要數(shù)據(jù)
-
Library/Preference:保存應用的偏好設置,iOS的settings應用會在該目錄中查找應用的設置信息诚撵,iTunes會同步
數(shù)據(jù)存儲
1.XML屬性列表(Plist)
- 存儲字典和數(shù)組缭裆,不能存儲自定義對象
- 判斷一個對象能不能使用plist就看有沒有
writeToFile
方法
2.Preference(偏好設置)
//存
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:@"xmg" forKey:@"account"];
[userDefaults setObject:@"123" forKey:@"pwd"];
[userDefaults setBool:YES forKey:@"rmbPwd"];
// 在iOS7之前键闺,默認不會馬上把跟硬盤同步
// 同步
[userDefaults synchronize];
//取
NSString *pwd = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwd"];
3.NSKeyedArchiver歸檔(NSCoding) / NSKeyedUnarchiver解檔
3.1Person
#import <Foundation/Foundation.h>
// 如果一個自定義對象想要歸檔寿烟,必須遵守NSCoding協(xié)議,實現(xiàn)協(xié)議方法辛燥。
@interface Person : NSObject <NSCoding>
@property (nonatomic, assign) int age;
@property (nonatomic, strong) NSString* name;
@end
#import "Person.h"
@implementation Person
// 什么時候調用:自定義對象歸檔的時候
// 作用:用來描述當前對象里面的哪些屬性需要歸檔
- (void)encodeWithCoder:(NSCoder *)aCoder
{
// name
[aCoder encodeObject:_name forKey:@"name"];
// age
[aCoder encodeInt:_age forKey:@"age"];
}
// 什么時候調用:解檔對象的時候調用
// 作用:用來描述當前對象里面的哪些屬性需要解檔
// initWithCoder:就是用來解析文件的筛武。
- (id)initWithCoder:(NSCoder *)aDecoder
{
// super:NSObject
if (self = [super init]) {
// 注意:一定要給成員變量賦值
// name
_name = [aDecoder decodeObjectForKey:@"name"];
// age
_age = [aDecoder decodeIntForKey:@"age"];
}
return self;
}
@end
//存
Person *p = [[Person alloc] init];
p.age = 18;
// 獲取cache
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 獲取文件的全路徑
NSString *filePath = [cachePath stringByAppendingPathComponent:@"person.data"];
// 把自定義對象歸檔
[NSKeyedArchiver archiveRootObject:p toFile:filePath];
//取
// 獲取cache
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
// 獲取文件的全路徑
NSString *filePath = [cachePath stringByAppendingPathComponent:@"person.data"];
// 解檔
Person *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
NSLog(@"%d",p.age);
3.2RedView
#import "RedView.h"
@implementation RedView
// 解析文件都會調用這個方法
// 因為Xib和Storyboard也屬于文件,所以通過Xib和Storyboard加載控件時會調用initWithCoder方法
- (id)initWithCoder:(NSCoder *)aDecoder
{
// 只要父類遵守了NSCoding,就調用initWithCoder
// 先初始化父類
if (self = [super initWithCoder:aDecoder]) {
NSLog(@"%s",__func__);
}
return self;
}
// 通過代碼初始化的時候挎塌,調用init方法徘六,底層就會調用initWithFrame
- (instancetype)initWithFrame:(CGRect)frame
{
if (self = [super initWithFrame:frame]) {
NSLog(@"%s",__func__);
}
return self;
}
@end
4.FMDB
JSON(NSJSONSerialization)
1.JSON -> NSData
[NSJSONSerialization JSONObjectWithData:
options:
error:];
options:
//返回可變容器,NSMutableDictionary或NSMutableArray
NSJSONReadingMutableContainers
//返回的JSON對象中字符串的值為NSMutableString
NSJSONReadingMutableLeaves
//允許JSON字符串最外層既不是NSArray也不是NSDictionary榴都,但必須是有效的JSON Fragment待锈。例如使用這個選項可以解析 @“123” 這樣的字符串
NSJSONReadingAllowFragments
2.NSData -> JSON
[NSJSONSerialization dataWithJSONObject:
options:
error:];
options:
NSJSONWritingPrettyPrinted
XML(NSXMLParser)
- 全稱是
Extensible Markup Language
,譯作“可擴展標記語言”
- 跟JSON一樣嘴高,也是常用的一種用于交互的數(shù)據(jù)格式
- 一般也叫XML文檔(XML Document)
- 一個常見的XML文檔一般由以下部分組成
文檔聲明
元素(Element)
屬性(Attribute)
- XML解析方式的選擇建議
-
大文件
:NSXMLParser竿音、libxml2(SAX
:從根元素開始,按順序一個元素一個元素往下解析)
-
小文件
:GDataXML拴驮、NSXMLParser春瞬、libxml2(DOM
:一次性將整個XML文檔加載進內存)
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:
[NSURLRequest requestWithURL:
[NSURL URLWithString:
@"http://120.25.226.186:32812/video?type=XML"]]
completionHandler:
^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
[parser parse];
}];
[task resume];
#pragma mark - <NSXMLParserDelegate>
//開始解析XML文檔
- (void)parserDidStartDocument:(NSXMLParser *)parser
//解析完畢
- (void)parserDidEndDocument:(NSXMLParser *)parser
//解析到某個元素的開頭(比如解析<videos>)
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary<NSString *,NSString *> *)attributeDict
//解析到某個元素的結尾(比如解析</videos>)
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
網(wǎng)絡--數(shù)據(jù)上傳
//創(chuàng)建url
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/upload"];
//創(chuàng)建請求對象
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST";
//設置請求對象的請求頭(告訴服務器這是一個上傳請求)
[request setValue:@"multipart/form-data; boundary=himyfairy88888" forHTTPHeaderField:@"Content-Type"];
//設置請求體
NSMutableData *data = [NSMutableData data];
//分割線
[data appendData:[@"--" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"himyfairy88888" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//文件參數(shù)名
[data appendData:[@"Content-Disposition: form-data; name=\"ql\"; filename=\"emoji-mosaic.jpg\"" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//文件的類型
[data appendData:[@"Content-Type: image/jpeg" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//文件數(shù)據(jù)
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[NSData dataWithContentsOfFile:@"/Users/Neo/Desktop/emoji-mosaic.jpg"]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
//結束標記
[data appendData:[@"--" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"himyfairy88888" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"--" dataUsingEncoding:NSUTF8StringEncoding]];
[data appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
request.HTTPBody = data;
[[[NSURLSession sharedSession] uploadTaskWithRequest:request fromData:data completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}] resume];
NSLog(@"upload執(zhí)行完畢");
NSURLSession
1.get
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建任務
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務
[task resume];
2.get簡略
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建任務
NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務
[task resume];
3.post
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 創(chuàng)建請求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login"]];
// 請求方法
request.HTTPMethod = @"POST";
// 請求體
request.HTTPBody = [@"username=520it&pwd=520it" dataUsingEncoding:NSUTF8StringEncoding];
// 創(chuàng)建任務
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(@"%@", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
}];
// 啟動任務
[task resume];
4.download
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sharedSession];
// 獲得下載任務
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"] completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {
// 文件將來存放的真實路徑(默認是放在tmp文件夾內)
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}];
// 啟動任務
[task resume];
5.NSURLSessionDataDelegate
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 創(chuàng)建任務
NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/login?username=123&pwd=4324"]]];
// 啟動任務
[task resume];
}
#pragma mark - <NSURLSessionDataDelegate>
/**
* 1.接收到服務器的響應
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
// 允許處理服務器的響應,才會繼續(xù)接收服務器返回的數(shù)據(jù)
completionHandler(NSURLSessionResponseAllow);
// void (^)(NSURLSessionResponseDisposition)
}
/**
* 2.接收到服務器的數(shù)據(jù)(可能會被調用多次)
*/
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
}
/**
* 3.請求成功或者失斕灼 (如果失敗宽气,error有值)
*/
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
}
6.大文件下載
#import "ViewController.h"
@interface ViewController () <NSURLSessionDownloadDelegate>
/** 下載任務 */
@property (nonatomic, strong) NSURLSessionDownloadTask *task;
@end
@implementation ViewController
//開始下載
- (IBAction)start:(id)sender {
// 獲得NSURLSession對象
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
// 獲得下載任務
self.task = [session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
// 啟動任務
[self.task resume];
}
//暫停下載
- (IBAction)pause:(id)sender {
[self.task suspend];
}
//繼續(xù)下載
- (IBAction)goOn:(id)sender {
[self.task resume];
}
#pragma mark - <NSURLSessionDownloadDelegate>
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
NSLog(@"didCompleteWithError");
}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
NSLog(@"didResumeAtOffset");
}
/**
* 每當寫入數(shù)據(jù)到臨時文件時,就會調用一次這個方法
* totalBytesExpectedToWrite:總大小
* totalBytesWritten: 已經(jīng)寫入的大小
* bytesWritten: 這次寫入多少
*/
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);
}
//下載完畢就會調用一次這個方法
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
// 文件將來存放的真實路徑
NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
// 剪切l(wèi)ocation的臨時文件到真實路徑
NSFileManager *mgr = [NSFileManager defaultManager];
[mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];
}
@end
NSStirng和NSDate轉換
- (NSString *)stringFromDate:(NSDate *)date
{
//設置Date格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//轉換為NSString
NSString *dateStr = [formatter stringFromDate:date];
return dateStr;
}
- (NSDate *)dateFromString:(NSString *)string
{
//設置Date格式
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//轉換為NSDate
NSDate *date = [formatter dateFromString:string];
return date;
}
Appearance
- 通過
appearance
統(tǒng)一設置所有UITabBarItem
的文字屬性潜沦,后面帶有UI_APPEARANCE_SELECTOR
的方法, 都可以通過appearance
對象來統(tǒng)一設置
[[UITabBarItem appearance] setTitleTextAttributes:@{
NSForegroundColorAttributeName : [UIColor colorWithRed:39 / 255.0 green:151 / 255.0 blue:217 / 255.0 alpha:1.0]
} forState:UIControlStateSelected];
tableViewCellSelection
2017-09-07 10:03:15.406427+0800 tableview[6810:2132107] shouldHighlightRow 1 - 3
2017-09-07 10:03:15.407568+0800 tableview[6810:2132107] didHighlighRow 1 - 3
2017-09-07 10:03:16.233114+0800 tableview[6810:2132107] didUnhighlightRow 1 - 3
2017-09-07 10:03:16.233356+0800 tableview[6810:2132107] willSelectRow 1 - 3
2017-09-07 10:03:16.234109+0800 tableview[6810:2132107] didSelectRow 1 - 3
2017-09-07 10:03:23.467563+0800 tableview[6810:2132107] shouldHighlightRow 1 - 10
2017-09-07 10:03:23.469080+0800 tableview[6810:2132107] didHighlighRow 1 - 10
2017-09-07 10:03:23.474551+0800 tableview[6810:2132107] didUnhighlightRow 1 - 10
2017-09-07 10:03:23.474739+0800 tableview[6810:2132107] willSelectRow 1 - 10
2017-09-07 10:03:23.474844+0800 tableview[6810:2132107] willDeselectRow 1 - 3
2017-09-07 10:03:23.474929+0800 tableview[6810:2132107] willDeselectRow 1 - 3
2017-09-07 10:03:23.475396+0800 tableview[6810:2132107] didDeselectRow 1 - 3
2017-09-07 10:03:23.476050+0800 tableview[6810:2132107] didSelectRow 1 - 10