系統彈窗:html
過時方法: UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"確認報價" message:@"報價不可修改" delegate:nil cancelButtonTitle:@"好的" otherButtonTitles: nil]; // 顯示出來 [alertView show]; 新方法: UIAlertController* alter = [UIAlertController alertControllerWithTitle:@"註銷帳戶" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; UIAlertAction* action1 = [UIAlertAction actionWithTitle:@"確認退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) { //填寫處理邏輯 }]; UIAlertAction* action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //填寫處理邏輯 }]; [alter addAction:action1]; [alter addAction:action2]; //彈出選擇框 [self presentViewController:alter animated:YES completion:nil];
定時器:ios
延遲調用方法一: [self performSelector:@selector(nextQuestion:) withObject:nil afterDelay:2.0]; 延遲調用方法二: dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ //須要調用的方法 }); 定時器一:(精確度通常): NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(方法名) userInfo:nil repeats:YES]; NSRunLoop *runLoop = [NSRunLoop mainRunLoop]; [runLoop addTimer:timer forMode:NSRunLoopCommonModes]; 定時器二:(精確度高): //1.建立CADisplayLink CADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(方法名)]; //2.添加到運行循環 [link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
計算控件尺寸:web
- (CGSize)stringSize:(NSString *) string andMaxSize:(CGSize)maxSize andFontNum:(NSInteger)fontNum{ // 最大尺寸 NSDictionary *dict = @{NSFontAttributeName : [UIFont systemFontOfSize:fontNum] }; CGRect labelFrame = [string boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil]; // 獲取 size並返回 return labelFrame.size; }
通知相關:正則表達式
發送通知 NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; [center postNotificationName:@"OpenButtonNotification" object:nil userInfo:@{@"headerView":self}]; 接收通知 NSNotificationCenter* center = [NSNotificationCenter defaultCenter]; [center addObserver:self selector:@selector(方法名:) name::@"OpenButtonNotification" object:nil]; 註銷通知 -(void)dealloc{ [[NSNotificationCenter defaultCenter] removeObserver:self]; }
TableView相關:數組
自動行高(須要配合autolayout自動佈局) self.tableView.estimatedRowHeight = 200; //預估行高 self.tableView.rowHeight = UITableViewAutomaticDimension;
tableViewCell左滑功能 //tableView向左滑的功能 -(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ self.tableView.editing = !self.tableView.editing; ChangeInfosController* changeInfo = [[ChangeInfosController alloc]init]; [self.navigationController pushViewController:changeInfo animated:YES]; } //修改左滑的文字 -(NSString*)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{ return @"編輯"; } 取消重用 NSString*CellIdentifier = [NSStringstringWithFormat:@"Cell%ld%ld", (long)[indexPath section], (long)[indexPath row]]; //以indexPath來惟一肯定cell FillOrderCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; //出列可重用的cell if (cell == nil) { cell = [[FillOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
CollectionView相關:緩存
自定義layout的三個步驟(流水佈局): 1、準備數據,並保存到佈局對象數組 - (void)prepareLayout{ [super prepareLayout]; //準備item的數據 //定義數組用來保存每一個item的frame NSMutableArray* marr = [NSMutableArray array]; //給每一個item佈局 for (int i = 0; i < self.clothesInfos.count; i ++) { //建立佈局對象 NSIndexPath* indexPath = [NSIndexPath indexPathForRow:i inSection:0]; UICollectionViewLayoutAttributes* attr = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath]; //取出數據 ClothesModel* model = self.clothesInfos[i]; //計算frame attr.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight); //保存數據 [marr addObject:attr]; } //計算footView的frame NSIndexPath* footPath = [NSIndexPath indexPathForRow:0 inSection:0]; UICollectionViewLayoutAttributes* footAtt = [UICollectionViewLayoutAttributes layoutAttributesForSupplementaryViewOfKind:UICollectionElementKindSectionFooter withIndexPath:footPath]; footAtt.frame = CGRectMake(footX, footY, footW, footH); [marr addObject:footAtt]; // 把數據保存到佈局數組 self.layoutAttributeMarr = marr; } 2、計算內容區域 - (CGSize)collectionViewContentSize{ CGFloat CVCWidth = [UIScreen mainScreen].bounds.size.width; UICollectionViewLayoutAttributes* lastAtt = self.layoutAttributeMarr.lastObject; CGFloat CVCHeight = CGRectGetMaxY(lastAtt.frame)+_margin;//根據最大的Y值獲得佈局內容的高度 CGSize CVCSize = CGSizeMake(CVCWidth, CVCHeight); return CVCSize; } 3、返回佈局對象數組 - (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect { return self.layoutAttributeMarr; }
數據存儲方式:安全
1.writeToFile 寫入數據: //1.1 你須要獲取路徑 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; // .XXX 尾椎 只是決定 以哪中方式查看數據, 對存入的數據自己沒有影響 NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"]; //1.2 寫數據 NSArray *dataArray = @[@"亞洲國際舞王尼古拉斯趙四",@"小明",@"老王",@"霜霜"];
//1.3 存 //atomically 原子性的,數據安全的, 百分之九十九都是YES [dataArray writeToFile:fiflePath atomically:YES]; 讀取數據: //1.讀取路徑 NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]; NSString *fiflePath = [path stringByAppendingPathComponent:@"data.XXX"]; //2.取出來 NSArray *dataArray = [NSArray arrayWithContentsOfFile:fiflePath]; 2.userDefault(偏好設置) 寫入數據: //1. 獲取系統的偏好設置對象 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //2. 存儲數據 [defaults setObject:@"小明" forKey:@"name"]; [defaults setInteger:100 forKey:@"age"]; [defaults setBool:NO forKey:@"isTrue"]; //3.當即同步: 強制寫入 [defaults synchronize]; 讀取數據: //1.獲取到偏好設置的路徑 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; //2.讀取數據 NSString *name = [defaults objectForKey:@"name"]; NSInteger age = [defaults integerForKey:@"age"]; BOOL isTrue = [defaults boolForKey:@"isTrue"]; 3.歸檔 寫入數據: //1.文件路徑 NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"]; //1. 有個對象 CZPserson *p = [[CZPserson alloc]init]; p.name = @"小明"; p.age = 100; p.sex = YES; //2.存儲 歸檔 [NSKeyedArchiver archiveRootObject:p toFile:filePath]; 讀取數據: 注意點: 若是使用歸檔 * 1. 該對象必須遵照NSCoding 協議 編碼協議 2. 實現 encodeWithCoder方法 3. 實現:initWIthCoder方法 NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"data.plist"]; //反歸檔 ,解檔 CZPserson *p = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; 實現<NSCoding>協議方法: - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeBool:self.sex forKey:@"sex"]; [aCoder encodeInteger:self.age forKey:@"age"]; [aCoder encodeObject:self.name forKey:@"name"]; } //反歸檔只是個過程, 告訴系統你讀取的時候,想讓別人讀取哪些屬性 - (instancetype)initWithCoder:(NSCoder *)aDecoder{ if (self = [super init]) { self.name = [aDecoder decodeObjectForKey:@"name"]; self.age = [aDecoder decodeIntegerForKey:@"age"]; self.sex = [aDecoder decodeBoolForKey:@"sex"]; } return self; }
隨機色:網絡
- (UIColor *)randomColor{
return [UIColor colorWithRed:((float)arc4random_uniform(256) / 255.0) green:((float)arc4random_uniform(256) / 255.0) blue:((float)arc4random_uniform(256) / 255.0) alpha:1.0];
}
手勢識別:app
UITapGestureRecognizer(點按) UILongPressGestureRecognizer(長按) UISwipeGestureRecognizer(輕掃) UIRotationGestureRecognizer(旋轉) UIPanGestureRecognizer(拖動) UIPinchGestureRecognizer(捏合,用於縮放) //1.建立一個手勢 而且監聽 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)]; //最小觸發 按壓的時間 longPress.minimumPressDuration = 2.0; //容許多大範圍內 觸發 longPress.allowableMovement = 20; //2.添加到當前你想 操做的控件上 [self.myImageVIew addGestureRecognizer:longPress];
時間相關:dom
獲取當前時間: 1.獲取當天的日期 NSDate *date = [NSDate date]; //2.獲取當前日曆 NSCalendar *lendar = [NSCalendar currentCalendar]; //3.從日曆中獲取 秒數 //(NSCalendarUnit) 單位 NSInteger second = [lendar component:NSCalendarUnitSecond fromDate:date]; 2.抓取系統時間 NSDate* nowDate = [NSDate date]; NSDateFormatter* formatter = [[NSDateFormatter alloc]init]; formatter.dateFormat = @"yyyy年MM月dd日HH時mm分ss秒"; NSString *time = [formatter stringFromDate:nowDate]; 判斷當前時間 -(BOOL)isToday{ NSCalendar *calendar=[NSCalendar currentCalendar]; NSCalendarUnit unit=NSCalendarUnitYear | NSCalendarUnitMonth |NSCalendarUnitDay; NSDateComponents *selfCmps=[calendar components:unit fromDate:self]; NSDateComponents *nowCmps=[calendar components:unit fromDate:[NSDate date]]; return selfCmps.year==nowCmps.year &&selfCmps.month==nowCmps.month &&selfCmps.day==nowCmps.day; } -(BOOL)isYesterday{ //生成只有年月日的日期對象 NSDateFormatter *fmt = [[NSDateFormatter alloc]init]; fmt.dateFormat=@"yyyy-MM-dd"; NSString *selfString =[fmt stringFromDate:self]; NSDate * selfDate=[fmt dateFromString:selfString]; NSString *nowString=[fmt stringFromDate:[NSDate date]]; NSDate *nowDate=[fmt dateFromString:nowString]; //比較差距 NSCalendar *calendar=[NSCalendar currentCalendar]; NSCalendarUnit unit=NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; NSDateComponents *cmps=[calendar components:unit fromDate:selfDate toDate:nowDate options:0]; return cmps.year==0 && cmps.month==0 && cmps.day==1 ; } -(BOOL)isTomorrow{ //生成只有年月日的日期對象 NSDateFormatter *fmr=[[NSDateFormatter alloc]init]; fmr.dateFormat=@"yyyy-MM-dd"; NSString *selfString=[fmr stringFromDate:self]; NSDate * selfDate=[fmr dateFromString:selfString]; NSString *nowString=[fmr stringFromDate:[NSDate date]]; NSDate *nowDate=[fmr dateFromString:nowString]; NSCalendar *calendar =[NSCalendar currentCalendar]; NSCalendarUnit unit=NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay; NSDateComponents *cmps=[calendar components:unit fromDate:selfDate toDate:nowDate options:0]; return cmps.year==0 && cmps.month==0 && cmps.day==-1; } -(BOOL)isThisYeas{ NSCalendar *calendar=[NSCalendar currentCalendar]; NSInteger selfYear=[calendar component:NSCalendarUnitYear fromDate:self]; NSInteger nowYear=[calendar component:NSCalendarUnitYear fromDate:[NSDate date]]; return selfYear==nowYear; }
動畫:
1.基礎動畫: //基礎動畫(縮放) CABasicAnimation* basic1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; basic1.toValue = @(0.1); //基礎動畫(旋轉) CABasicAnimation* basic2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; basic2.toValue = @(M_PI*2); 2.關鍵幀動畫: //建立路徑 UIBezierPath* path = [UIBezierPath bezierPathWithArcCenter:self.view.center radius:150 startAngle:0 endAngle:M_PI*2 clockwise:YES]; CAKeyframeAnimation* key = [CAKeyframeAnimation animationWithKeyPath:@"position"]; key.path = path.CGPath; 3.轉場動畫: //3.添加轉場動畫 CATransition *sition = [CATransition animation]; //設置屬性 //樣式 sition.type = kCATransitionMoveIn; //方向 sition.subtype = kCATransitionFromBottom; //添加動畫 [self.myImageView.layer addAnimation:sition forKey:nil]; 4.組動畫: //建立路徑 UIBezierPath* path = [UIBezierPath bezierPathWithArcCenter:self.view.center radius:150 startAngle:0 endAngle:M_PI*2 clockwise:YES]; //建立組動畫 CAAnimationGroup* group = [CAAnimationGroup animation]; //建立動畫1,關鍵幀動畫 CAKeyframeAnimation* key = [CAKeyframeAnimation animationWithKeyPath:@"position"]; key.path = path.CGPath; //建立動畫2,基礎動畫(縮放) CABasicAnimation* basic1 = [CABasicAnimation animationWithKeyPath:@"transform.scale"]; basic1.toValue = @(0.1); //建立動畫3,基礎動畫(旋轉) CABasicAnimation* basic2 = [CABasicAnimation animationWithKeyPath:@"transform.rotation"]; basic2.toValue = @(M_PI*2); //設置組動畫 group.animations = @[key,basic1,basic2]; group.duration = 2.0; group.repeatCount = 10; [self.myLayer addAnimation:group forKey:nil];
NavigationController相關:
設置導航欄外觀 NSDictionary *dict = @{ NSFontAttributeName:[UIFont systemFontOfSize:16], NSForegroundColorAttributeName:[UIColor whiteColor] }; [self.navigationBar setTitleTextAttributes:dict]; // 修改導航欄上的item的外觀 [self.navigationBar setTintColor:[UIColor whiteColor]]; 跳轉隱藏tabBar - (void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{ // 1.隱藏tabbar viewController.hidesBottomBarWhenPushed = YES; // 2.調用父類方法執行跳轉 [super pushViewController:viewController animated:YES]; } 設置狀態欄 - (UIStatusBarStyle)preferredStatusBarStyle{ return UIStatusBarStyleLightContent; }
加載本地的html:
// 建立一個url // NSURL *url = [NSURL URLWithString:@"https://www.baidu.com"]; NSURL *url = [[NSBundle mainBundle] URLForResource:self.help.html withExtension:nil]; // 建立一個請求對象 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 使用webView加載請求對象 [webView loadRequest:request]; // 開始加載 - (void)webViewDidStartLoad:(UIWebView *)webView{ NSLog(@"開始加載");} // 加載結束時執行Javascript代碼 - (void)webViewDidFinishLoad:(UIWebView *)webView{ // 須要執行的JavaScript代碼 NSString *jsCode = [NSString stringWithFormat:@"window.location.href = '#%@'",self.help.ID]; // webView執行js代碼 [webView stringByEvaluatingJavaScriptFromString:jsCode]; }
字符串轉對象:
// 獲取accessoryType NSString *accessoryType = item[@"accessoryType"]; // 根據字符串建立類 Class class = NSClassFromString(accessoryType); // 根據類實例化對象 UIView *accessoryView = [[class alloc] init]; // 判斷是不是UIImageView if ([accessoryView isKindOfClass:[UIImageView class]]) { // 強轉成UIImageView UIImageView *imgView = (UIImageView *)accessoryView; // 設置ImgView的圖片 imgView.image = [UIImage imageNamed:@"arrow_right"]; // 自適應大小 [imgView sizeToFit];
}
撥打電話:
//1.獲取APP 對象 UIApplication *app = [UIApplication sharedApplication]; //2.打電話 NSURL *url = [NSURL URLWithString:@"tel://1234567890"]; [app openURL:url]; //簡寫: [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel://1234567890"]];
應用程序之間跳轉:
NSURL *URL = [NSURL URLWithString:@"appB://ios.myapp.cn"]; [[UIApplication sharedApplication] openURL:URL];
裁剪圖片
//1.裁剪區域 CGRect rect = CGRectMake(x, y, w, h); // 2.調用系統的裁剪方法裁剪圖片 /* 參數: 1.被裁剪的大圖 CG類型 2.須要裁剪的區域 */ CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect); // 轉換成UIImage UIImage *img = [UIImage imageWithCGImage:imageRef]; // 釋放imageRef CGImageRelease(imageRef);
傳遞事件,判斷當前點是否在一個區域內
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{ // 1.描述一下按鈕上部分的區域 CGRect rect = CGRectMake(0, 0, self.bounds.size.width, 100); // 2.判斷當前點擊的點在不在上部分(若是不在,就直接返回nil) if (!CGRectContainsPoint(rect, point)) { return nil; } // 3.繼續傳遞事件 return [super hitTest:point withEvent:event]; }
從網絡獲取圖片
NSURL* url = [NSURL URLWithString:@"http://d.hiphotos.baidu.com/image/h%3D200/sign=c36bc6f3d32a28345ca6310b6bb4c92e/91ef76c6a7efce1b3e241e24a851f3deb58f65d5.jpg"];
NSData* data = [NSData dataWithContentsOfURL:url];
UIImage* image = [UIImage imageWithData:data];
開啓子線程
第一種方法 NSThread *thread1 = [[NSThread alloc]initWithTarget:self selector:@selector(buyTickets) object:nil]; //設置名稱 thread1.name = @"1111"; //設置優先級 thread1.threadPriority = 0.3; [thread1s start]; 第二種方法 [NSThread detachNewThreadSelector:@selector(buyTickets) toTarget:self withObject:nil]; 第三種方法 [self performSelectorInBackground:@selector(buyTickets) withObject:nil];
url中文和特殊字符轉碼
- (NSString *)generateUrl:(NSString *)url{
/** 第一個參數:NULL 第二個參數:C語言的字符串 第三個參數:NULL 第四個參數:要轉義的字符串,不要亂轉 第五個參數:編碼 */
NSString *encodedString = (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes( NULL,(__bridge CFStringRef)url,NULL,CFSTR("+"),CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding)); return encodedString;
}
數據加密
base64加密 加密 - (NSString *)base64Encode:(NSString *)originalString{ //1.將originalString轉成二進制 NSData *data = [originalString dataUsingEncoding:NSUTF8StringEncoding]; //2.須要將二進制轉成Base64加密以後的字符串 return [data base64EncodedStringWithOptions:0]; } 解密 - (NSString *)base64Decode:(NSString *)base64String{ //1.Base64加密以後的字符串轉成 NSData NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:0]; //2.將二進制轉在字符串 NSString *originalString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; return originalString; } 鑰匙串 //設置鑰匙串 self.bundleId = [NSBundle mainBundle].bundleIdentifier; NSString* value = [SSKeychain passwordForService:self.bundleId account:@"password"]; //保存密碼到鑰匙串 [SSKeychain setPassword:password forService:self.bundleId account:@"password"]; MD5/SHA //散列函數 - (NSString *)md5String { const char *str = self.UTF8String; uint8_t buffer[CC_MD5_DIGEST_LENGTH]; CC_MD5(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)sha1String { const char *str = self.UTF8String; uint8_t buffer[CC_SHA1_DIGEST_LENGTH]; CC_SHA1(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)sha256String { const char *str = self.UTF8String; uint8_t buffer[CC_SHA256_DIGEST_LENGTH]; CC_SHA256(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)sha512String { const char *str = self.UTF8String; uint8_t buffer[CC_SHA512_DIGEST_LENGTH]; CC_SHA512(str, (CC_LONG)strlen(str), buffer); return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - HMAC 散列函數 - (NSString *)hmacMD5StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_MD5_DIGEST_LENGTH]; CCHmac(kCCHmacAlgMD5, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)hmacSHA1StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_SHA1_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA1, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)hmacSHA256StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_SHA256_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA256, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)hmacSHA512StringWithKey:(NSString *)key { const char *keyData = key.UTF8String; const char *strData = self.UTF8String; uint8_t buffer[CC_SHA512_DIGEST_LENGTH]; CCHmac(kCCHmacAlgSHA512, keyData, strlen(keyData), strData, strlen(strData), buffer); return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - 文件散列函數 #define FileHashDefaultChunkSizeForReadingData 4096 - (NSString *)fileMD5Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_MD5_CTX hashCtx; CC_MD5_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_MD5_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_MD5_DIGEST_LENGTH]; CC_MD5_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_MD5_DIGEST_LENGTH]; } - (NSString *)fileSHA1Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_SHA1_CTX hashCtx; CC_SHA1_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_SHA1_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_SHA1_DIGEST_LENGTH]; CC_SHA1_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_SHA1_DIGEST_LENGTH]; } - (NSString *)fileSHA256Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_SHA256_CTX hashCtx; CC_SHA256_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_SHA256_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_SHA256_DIGEST_LENGTH]; CC_SHA256_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_SHA256_DIGEST_LENGTH]; } - (NSString *)fileSHA512Hash { NSFileHandle *fp = [NSFileHandle fileHandleForReadingAtPath:self]; if (fp == nil) { return nil; } CC_SHA512_CTX hashCtx; CC_SHA512_Init(&hashCtx); while (YES) { @autoreleasepool { NSData *data = [fp readDataOfLength:FileHashDefaultChunkSizeForReadingData]; CC_SHA512_Update(&hashCtx, data.bytes, (CC_LONG)data.length); if (data.length == 0) { break; } } } [fp closeFile]; uint8_t buffer[CC_SHA512_DIGEST_LENGTH]; CC_SHA512_Final(buffer, &hashCtx); return [self stringFromBytes:buffer length:CC_SHA512_DIGEST_LENGTH]; } #pragma mark - 助手方法 /** * 返回二進制 Bytes 流的字符串表示形式 * * @param bytes 二進制 Bytes 數組 * @param length 數組長度 * * @return 字符串表示形式 */ - (NSString *)stringFromBytes:(uint8_t *)bytes length:(int)length { NSMutableString *strM = [NSMutableString string]; for (int i = 0; i < length; i++) { [strM appendFormat:@"%02x", bytes[i]]; } return [strM copy]; }
解壓縮文件
//下載完畢解壓到當前文件夾 [SSZipArchive unzipFileAtPath:location.path toDestination:self.destinationPath uniqueId:nil];
數組排序
[marr sortUsingComparator:^NSComparisonResult(NewsModel* model1, NewsModel* model2) { return [model1.num compare: model2.num]; }];
數組倒序
NSArray* arr = [[ordersMarr reverseObjectEnumerator] allObjects];
NSArray 快速求總和、最大值、最小值、平均值
- (void)caculateArray:(NSArray *)array{ CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue]; CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue]; CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue]; CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%fn%fn%fn%f",sum,avg,max,min); return [NSString stringWithFormat:@"%f",sum]; }
字符串排序分組
將字符串數組按照元素首字母順序進行排序分組 + (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{ if (array.count == 0) { return nil; } for (id obj in array) { if (![obj isKindOfClass:[NSString class]]) { return nil; } } UILocalizedIndexedCollation *indexedCollation = [UILocalizedInd exedCollation currentCollation]; NSMutableArray *objects = [NSMutableArray arrayWithCapacity:indexedCollation.sectionTitles.count]; //建立27個分組數組 for (int i = 0; i < indexedCollation.sectionTitles.count; i++) { NSMutableArray *obj = [NSMutableArray array]; [objects addObject:obj]; } NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count]; //按字母順序進行分組 NSInteger lastIndex = -1; for (int i = 0; i < array.count; i++) { NSInteger index = [indexedCollation sectionForObject:array[i] collationStringSelector:@selector(uppercaseString)]; [[objects objectAtIndex:index] addObject:array[i]]; lastIndex = index; } //去掉空數組 for (int i = 0; i < objects.count; i++) { NSMutableArray *obj = objects[i]; if (obj.count == 0) { [objects removeObject:obj]; } } //獲取索引字母 for (NSMutableArray *obj in objects) { NSString *str = obj[0]; NSString *key = [self firstCharacterWithString:str]; [keys addObject:key]; } NSMutableDictionary *dic = [NSMutableDictionary dictionary]; [dic setObject:objects forKey:keys]; return dic; }
計算磁盤大小
1.磁盤總空間大小 + (CGFloat)diskOfAllSizeMBytes{ CGFloat size = 0.0; NSError *error; NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) { #ifdef DEBUG NSLog(@"error: %@", error.localizedDescription); #endif }else{ NSNumber *number = [dic objectForKey:NSFileSystemSize]; size = [number floatValue]/1024/1024; } return size; } 2.磁盤可用空間大小 + (CGFloat)diskOfFreeSizeMBytes{ CGFloat size = 0.0; NSError *error; NSDictionary *dic = [[NSFileManager defaultManager] attributesOfFileSystemForPath:NSHomeDirectory() error:&error]; if (error) { #ifdef DEBUG NSLog(@"error: %@", error.localizedDescription); #endif }else{ NSNumber *number = [dic objectForKey:NSFileSystemFreeSize]; size = [number floatValue]/1024/1024; } return size; }
相冊選擇多文件(ZLPhotos)
//進入相冊 ZLPhotoPickerViewController* imgPickerController = [[ZLPhotoPickerViewController alloc]init]; imgPickerController.status = PickerViewShowStatusSavePhotos; imgPickerController.maxCount = 3; //設置最大可選擇數 [self presentViewController:imgPickerController animated:YES completion:nil]; //block傳值 __weak typeof(self) weakSelf = self; imgPickerController.callBack = ^(NSArray *assets){ for (ZLPhotoAssets *photoAsset in assets) { UIImage *image = photoAsset.originImage; NSData *imageData =UIImagePNGRepresentation(image); //隨機生成的文件名稱 NSString *fileName = [NSString stringWithFormat:@"%d.png",arc4random_uniform(100)];
//將每次獲取到的圖片,加入到字典中 [weakSelf.fileDict setObject:imageData forKey:fileName]; } };
圖片處理
對圖片進行濾鏡處理 // 懷舊 --> CIPhotoEffectInstant 單色 --> CIPhotoEffectMono // 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade // 色調 --> CIPhotoEffectTonal 沖印 --> CIPhotoEffectProcess // 歲月 --> CIPhotoEffectTransfer 鉻黃 --> CIPhotoEffectChrome // CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField + (UIImage *)filterWithOriginalImage:(UIImage *)image filterName:(NSString *)name{ CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage = [[CIImage alloc] initWithImage:image]; CIFilter *filter = [CIFilter filterWithName:name]; [filter setValue:inputImage forKey:kCIInputImageKey]; CIImage *result = [filter valueForKey:kCIOutputImageKey]; CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]]; UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return resultImage; } 對圖片進行模糊處理 // CIGaussianBlur ---> 高斯模糊 // CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later) // CIDiscBlur ---> 環形卷積模糊(Available in iOS 9.0 and later) // CIMedianFilter ---> 中值模糊, 用於消除圖像噪點, 無需設置radius(Available in iOS 9.0 and later) // CIMotionBlur ---> 運動模糊, 用於模擬相機移動拍攝時的掃尾效果(Available in iOS 9.0 and later) + (UIImage *)blurWithOriginalImage:(UIImage *)image blurName:(NSString *)name radius:(NSInteger)radius{ CIContext *context = [CIContext contextWithOptions:nil]; CIImage *inputImage = [[CIImage alloc] initWithImage:image]; CIFilter *filter; if (name.length != 0) { filter = [CIFilter filterWithName:name]; [filter setValue:inputImage forKey:kCIInputImageKey]; if (![name isEqualToString:@"CIMedianFilter"]) { [filter setValue:@(radius) forKey:@"inputRadius"]; } CIImage *result = [filter valueForKey:kCIOutputImageKey]; CGImageRef cgImage = [context createCGImage:result fromRect: [result extent]]; UIImage *resultImage = [UIImage imageWithCGImage:cgImage]; CGImageRelease(cgImage); return resultImage; } else { return nil; } } 毛玻璃效果 //Avilable in iOS 8.0 and later + (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{ UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]; UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect]; effectView.frame = frame; return effectView; } 給image設置尺寸(縮放圖片) - (UIImage *)imageByScalingToSize:(CGSize)targetSize{ UIImage *sourceImage = self; UIImage *newImage = nil; CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width; CGFloat targetHeight = targetSize.height; CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) ==NO) { CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor < heightFactor) scaleFactor = widthFactor; else scaleFactor = heightFactor; scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; if (widthFactor < heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor > heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } UIGraphicsBeginImageContext(targetSize); CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width = scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; newImage =UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); if(newImage == nil) NSLog(@"could not scale image"); return newImage ; }
設置Label的行間距
+ (void)setLineSpaceWithString:(UILabel *)label{ NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:label.text]; NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init]; [paragraphStyle setLineSpacing:3]; //調整行間距 [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [label.text length])]; label.attributedText = attributedString; } 設置Label裏的字符有不一樣的顏色 //可根據本身的需求進行增刪改 - (void)stringColorSet { NSString*string = @"如何使得Label裏的字符有不一樣的顏色?"; NSRange range = [string rangeOfString: @"Label"]; NSMutableAttributedString*attribute = [[NSMutableAttributedString alloc] initWithString: string]; [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor redColor]}range: range]; [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor greenColor]}range: NSMakeRange(0, range.location)]; [attribute addAttributes: @{NSForegroundColorAttributeName: [UIColor cyanColor]}range: NSMakeRange(range.location+ range.length, 5)]; UILabel *label = [[UILabel alloc] initWithFrame: CGRectMake(0.0f, 100.0f, 320.0f, 100.0f)]; [label setText: string]; [label setAttributedText: attribute];} 設置label顯示多行文字 let lab = UILabel() let title = "立刻登錄\n\n開啓個人奇妙之旅~" //富文本單獨設置後面的名稱 let attr = NSMutableAttributedString(string: title) //獲取名字範圍 let range = (title as NSString).rangeOfString("開啓個人奇妙之旅~") //單獨設置制定範圍的字符串 attr.addAttributes([NSForegroundColorAttributeName : UIColor.lightGrayColor(),NSFontAttributeName : UIFont.systemFontOfSize(12)], range: range) //賦值 lab.attributedText = attire //設置換行 lab.numberOfLines = 0 //設置文字大小 lab.font = UIFont.systemFontOfSize(14) //文字顏色 lab.textColor = UIColor.grayColor() //文字居中 lab.textAlignment = .Center
信息驗證
判斷手機號碼格式是否正確,利用正則表達式驗證 + (BOOL)isMobileNumber:(NSString *)mobileNum{ if (mobileNum.length != 11) { return NO; } /** * 手機號碼: * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[6, 7, 8], 18[0-9], 170[0-9] * 移動號段: 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705 * 聯通號段: 130,131,132,155,156,185,186,145,176,1709 * 電信號段: 133,153,180,181,189,177,1700 * / NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|70)\d{8}$"; /** * 中國移動:China Mobile * 134,135,136,137,138,139,150,151,152,157,158,159,182,183,184,187,188,147,178,1705 */ NSString *CM = @"(^1(3[4-9]|4[7]|5[0-27-9]|7[8]|8[2-478])\d{8}$)|(^1705\d{7}$)"; /** * 中國聯通:China Unicom * 130,131,132,155,156,185,186,145,176,1709 */ NSString *CU = @"(^1(3[0-2]|4[5]|5[56]|7[6]|8[56])\d{8}$)|(^1709\d{7}$)"; /** * 中國電信:China Telecom * 133,153,180,181,189,177,1700 */ NSString *CT = @"(^1(33|53|77|8[019])\d{8}$)|(^1700\d{7}$)"; NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE]; NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM]; NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU]; NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT]; if (([regextestmobile evaluateWithObject:mobileNum] == YES) || ([regextestcm evaluateWithObject:mobileNum] == YES) || ([regextestct evaluateWithObject:mobileNum] == YES) || ([regextestcu evaluateWithObject:mobileNum] == YES)) { return YES; } else { return NO; } } 2. 判斷郵箱格式是否正確,利用正則表達式驗證 + (BOOL)isAvailableEmail:(NSString *)email{ NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}"; NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex]; return [emailTest evaluateWithObject:email]; } 3. 判斷字符串中是否含有空格 + (BOOL)isHaveSpaceInString:(NSString *)string{ NSRange _range = [string rangeOfString:@" "]; if (_range.location != NSNotFound) { return YES; }else { return NO; } } 4. 判斷字符串中是否含有中文 + (BOOL)isHaveChineseInString:(NSString *)string{ for(NSInteger i = 0; i < [string length]; i++){ int a = [string characterAtIndex:i]; if (a > 0x4e00 && a < 0x9fff) { return YES; } } return NO; } 判斷身份證格式 + (BOOL)checkIdentityCardNo:(NSString*)value { value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; NSInteger length =0; if (!value) { return NO; }else { length = value.length; if (length !=15 && length !=18) { return NO; } } // 省份代碼 NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"]; NSString *valueStart2 = [value substringToIndex:2]; BOOL areaFlag =NO; for (NSString *areaCode in areasArray) { if ([areaCode isEqualToString:valueStart2]) { areaFlag =YES; break; } } if (!areaFlag) { return false; } NSRegularExpression *regularExpression; NSUInteger numberofMatch; NSInteger year =0; switch (length) { case 15: year = [[value substringWithRange:NSMakeRange(6,2)] integerValue] +1900; if (year %4 ==0 || (year 0 ==0 && year %4 ==0)) { regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性 }else { regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性 } numberofMatch = [regularExpression numberOfMatchesInString:value options:NSMatchingReportProgress range:NSMakeRange(0, value.length)]; if(numberofMatch >0) { return YES; }else { return NO; } case 18: year = [value substringWithRange:NSMakeRange(6,4)].intValue; if (year %4 ==0 || (year 0 ==0 && year %4 ==0)) { regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性 }else { regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$" options:NSRegularExpressionCaseInsensitive error:nil];//測試出生日期的合法性 } numberofMatch = [regularExpression numberOfMatchesInString:value options:NSMatchingReportProgress range:NSMakeRange(0, value.length)]; if(numberofMatch >0) { int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3; int Y = S ; NSString *M =@"F"; NSString *JYM =@"10X98765432"; M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判斷校驗位 if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) { return YES;// 檢測ID的校驗位 }else { return NO; } }else { return NO; } default: return false; } }
經常使用函數:
rand() ----隨機數 abs() / labs() ----整數絕對值 fabs() / fabsf() / fabsl() ----浮點數絕對值 floor() / floorf() / floorl() ----向下取整 ceil() / ceilf() / ceill() ----向上取整 round() / roundf() / roundl() ----四捨五入 sqrt() / sqrtf() / sqrtl() ----求平方根 fmax() / fmaxf() / fmaxl() ----求最大值 fmin() / fminf() / fminl() ----求最小值 hypot() / hypotf() / hypotl() ----求直角三角形斜邊的長度 fmod() / fmodf() / fmodl() ----求兩數整除後的餘數 modf() / modff() / modfl() ----浮點數分解爲整數和小數 frexp() / frexpf() / frexpl() ----浮點數分解尾數和二爲底的指數 sin() / sinf() / sinl() ----求正弦值 sinh() / sinhf() / sinhl() ----求雙曲正弦值 cos() / cosf() / cosl() ----求餘弦值 cosh() / coshf() / coshl() ----求雙曲餘弦值 tan() / tanf() / tanl() ----求正切值 tanh() / tanhf() / tanhl() ----求雙曲正切值 asin() / asinf() / asinl() ----求反正弦值 asinh() / asinhf() / asinhl() ----求反雙曲正弦值 acos() / acosf() / acosl() ----求反餘弦值 acosh() / acoshf() / acoshl() ----求反雙曲餘弦值 atan() / atanf() / atanl() ----求反正切值 atan2() / atan2f() / atan2l() ----求座標值的反正切值 atanh() / atanhf() / atanhl() ----求反雙曲正切值
判斷手勢方向:
CGPoint translation = [scrollView.panGestureRecognizer translationInView:scrollView.superview]; if (translation.y>0) { // NSLog(@"----------下-----------"); }else if(translation.y<0){ // NSLog(@"----------上-----------"); }
獲取路徑下文件大小
- (unsigned long long)fileSizes{ // 得到文件管理者 NSFileManager *mgr = [NSFileManager defaultManager]; // 是否爲文件夾 BOOL isDirectory = NO; // 先判斷路徑的存在性 BOOL exists = [mgr fileExistsAtPath:self isDirectory:&isDirectory]; // 路徑不存在 if (!exists) return 0; // 若是是文件夾 if (isDirectory) { // 文件總大小 unsigned long long fileSize = 0; // 遍歷全部文件 NSDirectoryEnumerator *enumerator = [mgr enumeratorAtPath:self]; for (NSString *subpath in enumerator) { // 完整的子路徑 NSString *fullSubpath = [self stringByAppendingPathComponent:subpath]; fileSize += [mgr attributesOfItemAtPath:fullSubpath error:nil].fileSize; } return fileSize; } // 若是是文件 return [mgr attributesOfItemAtPath:self error:nil].fileSize; }
獲取設備型號
+ (NSString *)platform{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size); sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
free(machine);
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4 (GSM)";
if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4 (CDMA)";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6Plus GSM";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6 GSM+CDMA";
if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s GSM";
if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus Global";
if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (GSM)";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (CDMA)";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini (GSM)";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini (GSM+CDMA)";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (GSM+CDMA)";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (GSM)";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (GSM)";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (GSM+CDMA)";
if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (GSM)";
if ([platform isEqualToString:@"iPad4,4"]) return @"iPad Mini Retina (WiFi)";
if ([platform isEqualToString:@"iPad4,5"]) return @"iPad Mini Retina (GSM)";
if ([platform isEqualToString:@"i386"]) return @"Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
return platform; }
緩存處理
緩存路徑 #define CacheFilePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] 清空緩存 +(BOOL)CleanCacheFilePath{ //拿到path路徑的下一級目錄的子文件夾 NSArray *subPathArr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:CacheFilePath error:nil]; NSString *filePath = nil; NSError *error = nil; for (NSString *subPath in subPathArr) { filePath = [CacheFilePath stringByAppendingPathComponent:subPath]; //刪除子文件夾 [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; if (error) { NSLog(@"%@",error); continue; } } return YES; } 緩存計算 //轉換B/KB/MB/GB +(NSString *)SetCacheSize:(unsigned long long)fileSize{ // 單位 double unit = 1000.0; // 標籤文字 NSString *fileSizeText = nil; if (fileSize >= pow(unit, 3)) { // fileSize >= 1GB fileSizeText = [NSString stringWithFormat:@"%.2fGB", fileSize / pow(unit, 3)]; } else if (fileSize >= pow(unit, 2)) { // fileSize >= 1MB fileSizeText = [NSString stringWithFormat:@"%.2fMB", fileSize / pow(unit, 2)]; } else if (fileSize >= unit) { // fileSize >= 1KB fileSizeText = [NSString stringWithFormat:@"%.2fKB", fileSize / unit]; } else { // fileSize < 1KB fileSizeText = [NSString stringWithFormat:@"%zdB", fileSize]; } return fileSizeText; }
給TabBarController添加滑動切換
//添加滑動手勢 UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedRightButton:)]; [swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft]; [self.view addGestureRecognizer:swipeLeft]; UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(tappedLeftButton:)]; [swipeRight setDirection:UISwipeGestureRecognizerDirectionRight]; [self.view addGestureRecognizer:swipeRight];
- (void) tappedRightButton:(id)sender{
NSUInteger selectedIndex = [self.tabBarController selectedIndex]; NSArray *aryViewController = self.tabBarController.viewControllers; if (selectedIndex < aryViewController.count - 1) { [self.tabBarController setSelectedIndex:selectedIndex + 1]; } } - (void) tappedLeftButton:(id)sender{ NSUInteger selectedIndex = [self.tabBarController selectedIndex]; if (selectedIndex > 0) { [self.tabBarController setSelectedIndex:selectedIndex - 1]; } }