iOS开发中常用的方法

系统弹窗:

过期方法:
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];

定时器:

延迟调用方法一:
[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.创建CADisplayLinkCADisplayLink *link = [CADisplayLink displayLinkWithTarget:self selector:@selector(方法名)];
//2.添加到运行循环[link addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

计算控件尺寸:

- (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的三个步骤(流水布局):
一、准备数据,并保存到布局对象数组
- (void)prepareLayout{   [super prepareLayout]; //准备item的数据 //定义数组用来保存每个item的frameNSMutableArray* 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];//计算frameattr.frame = CGRectMake(itemX, itemY, itemWidth, itemHeight);//保存数据
    [marr addObject:attr];}//计算footView的frameNSIndexPath* 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;
}
二、计算内容区域
- (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;
}
三、返回布局对象数组
- (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]; }

手势识别:

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];

时间相关:

获取当前时间:
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];}
}

强则戒骄逸,处安已备。弱则暗图强,待机而动。

iOS开发中常用的方法相关推荐

  1. iOS开发中 常用枚举和常用的一些运算符(易错总结)

    1.色值的随机值: #define kColorValue arc4random_uniform(256)/255.0 // arc4random_uniform(256)/255.0; 求出0.0~ ...

  2. ios开发中常用的几种辅助方法

    //1.Keychain本地长期键值存储 //删除 +(void)deleteStringForKey:(NSString *)aKey {NSMutableDictionary *query = [ ...

  3. IOS开发之----常用加密方法

    本文转载至 http://blog.csdn.net/wildfireli/article/details/23191983 (AES.MD5.Base64) 分类: iPhone 2014-04-0 ...

  4. iOS开发中常用到的第三方库

    整理了学习iOS之后常用的第三方库,后续有其他的会继续更新 希望可以帮助到你 网络请求: AFNetworking Alamofire 博客提到过https://blog.csdn.net/weixi ...

  5. iOS开发中常用的那些工具

    工欲善其事,必先利其器. 列表 XCode 无须多说 Instruments 性能分析工具:卡顿,内存,网络,数据存储等等 xcodebuild and xcrun 命令行工具用来脚本打包和测试 sy ...

  6. iOS开发中常用的第三方插件和框架小结

    一:插件 1.图片补全插件:(1)比如说你只有@3x的图片想要@2x的图片又不想麻烦美工妹妹,即可使用此神器:https://github.com/rickytan/RTImageAssets (2) ...

  7. CJBorderView 一种iOS开发中常用的虚线边框View------* An easy way to init a view with dotted line border

    CJBorderView An easy way to init a view with dotted line border Author:CoderChenJun Email:Coder.Chen ...

  8. ios开发中常用的一些软件

    数据库:SQLManager.SQLite Professional.Navicat Premium. 快速查看模拟器沙盒文件夹:SimPholders (https://simpholders.co ...

  9. iOS开发中常用的几个苹果网站

    证书网站:https://developer.apple.com/membercenter/index.action iTunes网站:https://itunesconnect.apple.com ...

最新文章

  1. python3 flask sqlalchemy 数据库操作
  2. hex editor怎么搜索代码_代码审计从入门到放弃(三) phplimit
  3. zzuliOJ【土豪婷婷请吃饭】【解法:Java二维数组】
  4. 开箱即用——用这个模板快速统筹企业车辆安排
  5. 【转】知道这20个正则表达式,能让你少写1,000行代码
  6. 阿里巴巴对Java编程【应用结构】的规约
  7. Supervisor管理springboot应用进程
  8. 体验QQ2011Beta3带来的变化和惊喜
  9. Unit4中的Annotation
  10. python人名最多数统计_《利用Python进行数据分析》-全美婴儿姓名案例
  11. 《分布式系统原理与范型》习题答案 5.同步
  12. 2019互联网寒冬期IT大牛不容错过的泰牛程序员PHP系列高级教程
  13. 冒险者传说pc6java_我的世界之冒险者传说整合包游戏
  14. FlashFXP、LeapFTP、CuteFTP 等FTP软件二进制上传或下载方法
  15. 未知错误,可能由于拨号连接未创建成功
  16. Linux创建磁盘并分区命令
  17. PHP 创建与解析 XML
  18. Springboot(SpringBoot)重试机制retry
  19. 能把中文论文翻译成英文进行查重吗?
  20. 剖析Mozilla代码之七武器

热门文章

  1. 远程桌面 - linux
  2. vue-amap 高德地图中使用测距插件
  3. U盘安装Fedora 24时出现的几个问题及解决办法
  4. mysql期末作业_MySql期中作业
  5. Centos升级Chrome浏览器
  6. 【IT职场】如何成为T型甚至A型人物。
  7. AI之Tool:GitHub Copilot(一款人工智能编程小助手—猜你想写的代码)的简介、安装、使用方法之详细攻略
  8. 2023 闲鱼扫码自动收货跳转支付宝HTML源码
  9. 计算机网络应用最简单的,计算机网络的基础知识和简单应用.ppt
  10. 花边新闻获取易语言代码