iOS一些常用的判断

# ios常用的一些判断

## 根据日起计算是周几

```

+ (NSString*)weekdayStringFromDate:(NSDate*)inputDate

{

NSArray *weekdays = [NSArray arrayWithObjects: [NSNull null], @"周日", @"周一", @"周二", @"周三", @"周四", @"周五", @"周六", nil];

NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];

[calendar setTimeZone: timeZone];

NSCalendarUnit calendarUnit = NSWeekdayCalendarUnit;

NSDateComponents *theComponents = [calendar components:calendarUnit fromDate:inputDate];

return [weekdays objectAtIndex:theComponents.weekday];

}

```

## 把时间戳转化为字符串

### 传个时间转化为字符串

```

+ (NSString *)dateStringFromNumberTimer:(NSString *)timerStr {

//转化为Double

double t = [timerStr doubleValue];

//计算出距离1970的NSDate

NSDate *date = [NSDate dateWithTimeIntervalSince1970:t];

//转化为 时间格式化字符串

//NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];

NSDateFormatter *df = [[NSDateFormatter alloc] init];

df.dateFormat = @"yyyy-MM-dd HH:mm:ss";

//转化为 时间字符串

return [df stringFromDate:date];

}

```

### 计算时间差

获得当前系统时间到指定时间的时间差字符串,传入目标时间字符串和格式

```

+(NSString*)stringNowToDate:(NSString*)toDate formater:(NSString*)formatStr

{

NSDateFormatter *formater=[[NSDateFormatter alloc] init];

if (formatStr) {

[formater setDateFormat:formatStr];

}

else{

[formater setDateFormat:[NSString stringWithFormat:@"yyyy-MM-dd HH:mm:ss"]];

}

NSDate *date=[formater dateFromString:toDate];

return [self stringNowToDate:date];

}

```

获得到指定时间的时间差字符串,格式在此方法内返回前自己根据需要格式化

```

+(NSString*)stringNowToDate:(NSDate*)toDate

{

//创建日期 NSCalendar对象

NSCalendar *cal = [NSCalendar currentCalendar];

//得到当前时间

NSDate *today = [NSDate date];

//用来得到具体的时差,位运算

unsigned int unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ;

if (toDate && today) {//不为nil进行转化

NSDateComponents *d = [cal components:unitFlags fromDate:today toDate:toDate options:0 ];

//NSString *dateStr=[NSString stringWithFormat:@"%d年%d月%d日%d时%d分%d秒",[d year],[d month], [d day], [d hour], [d minute], [d second]];

NSString *dateStr=[NSString stringWithFormat:@"%02ld:%02ld:%02ld",[d hour], [d minute], [d second]];

return dateStr;

}

return @"";

}

```

## 动态计算行高

根据字符串的实际内容大小,在固定的宽度和大小的情况下,动态计算行高

```

+ (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{

if ([MZLUtility getCurrentIOS] >= 7.0) {

//iOS7之后

/*

第一个参数: 预设空间 宽度固定  高度预设 一个最大值

第二个参数: 行间距 如果超出范围是否截断

第三个参数: 属性字典 可以设置字体大小

*/

NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};

CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];

//返回计算出的行高

return rect.size.height;

}else {

//iOS7之前

/*

1.第一个参数  设置的字体固定大小

2.预设 宽度和高度 宽度是固定的 高度一般写成最大值

3.换行模式 字符换行

*/

CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(textWidth, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];

return textSize.height;//返回 计算出得行高

}

}

```

## 获取iOS的版本号

```

+ (double)getCurrentIOS {

return [[[UIDevice currentDevice] systemVersion] doubleValue];

}

+ (CGSize)getScreenSize {

return [[UIScreen mainScreen] bounds].size;

}

```

## 目录

### 找到沙盒的路径

```

+ (NSString *)getFullPathWithFile:(NSString *)urlName {

//先获取 沙盒中的Library/Caches/路径

NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];

NSString *myCacheDirectory = [docPath stringByAppendingPathComponent:@"MyCaches"];

//检测MyCaches 文件夹是否存在

if (![[NSFileManager defaultManager] fileExistsAtPath:myCacheDirectory]) {

//不存在 那么创建

[[NSFileManager defaultManager] createDirectoryAtPath:myCacheDirectory withIntermediateDirectories:YES attributes:nil error:nil];

}

//用md5进行 加密 转化为 一串十六进制数字 (md5加密可以把一个字符串转化为一串唯一的用十六进制表示的串)

NSString * newName = MD5Hash(urlName);

//拼接路径

return [myCacheDirectory stringByAppendingPathComponent:newName];

}

```

### 清除缓存

```

+ (void) resetCache {

[[NSFileManager defaultManager] removeItemAtPath:[MZLCache cacheDirectory] error:nil];

}

```

### 缓存目录

```

+ (NSString*) cacheDirectory {

NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

NSString *cacheDirectory = [paths objectAtIndex:0];

cacheDirectory = [cacheDirectory stringByAppendingPathComponent:@"MZLCaches"];

return cacheDirectory;

}

```

### 删除指定的缓存

```

+ (NSData*) objectForKey:(NSString*)key {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];

if ([fileManager fileExistsAtPath:filename])

{

NSDate *modificationDate = [[fileManager attributesOfItemAtPath:filename error:nil] objectForKey:NSFileModificationDate];

if ([modificationDate timeIntervalSinceNow] > cacheTime) {

[fileManager removeItemAtPath:filename error:nil];

} else {

NSData *data = [NSData dataWithContentsOfFile:filename];

return data;

}

}

return nil;

}

```

### 创建指定的缓存

```

+ (void) setObject:(NSData*)data forKey:(NSString*)key {

NSFileManager *fileManager = [NSFileManager defaultManager];

NSString *filename = [self.cacheDirectory stringByAppendingPathComponent:key];

BOOL isDir = YES;

if (![fileManager fileExistsAtPath:self.cacheDirectory isDirectory:&isDir]) {

[fileManager createDirectoryAtPath:self.cacheDirectory withIntermediateDirectories:NO attributes:nil error:nil];

}

NSError *error;

@try {

[data writeToFile:filename options:NSDataWritingAtomic error:&error];

}

@catch (NSException * e) {

//TODO: error handling maybe

}

}

```

### 获取某个路径下文件的大小

```

+ (long long) fileSizeAtPath:(NSString*) filePath{

NSFileManager* manager = [NSFileManager defaultManager];

if ([manager fileExistsAtPath:filePath]){

return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];

}

return 0;

}

```

### 获取缓存的大小

```

+ (float ) folderSizeAtPath:(NSString*) folderPath{

NSFileManager* manager = [NSFileManager defaultManager];

if (![manager fileExistsAtPath:folderPath])

return 0;

NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];

NSString* fileName;

long long folderSize = 0;

while ((fileName = [childFilesEnumerator nextObject]) != nil){

NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];

folderSize += [MZLCache fileSizeAtPath:fileAbsolutePath];

}

return folderSize/(1024.0*1024.0);

}

```

## MD5加密字符串

```

NSString * MD5Hash(NSString *aString) {

const char *cStr = [aString UTF8String];

unsigned char result[16];

CC_MD5( cStr, (CC_LONG)strlen(cStr), result );

return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",

result[0], result[1], result[2], result[3],

result[4], result[5], result[6], result[7],

result[8], result[9], result[10], result[11],

result[12], result[13], result[14], result[15]];

}

```

## 正则判断

### 手机格式的正则判断

```

+ (BOOL)isMobileNumber:(NSString *)mobileNum

{

/**

* 手机号码

* 移动:134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188

* 联通:130,131,132,152,155,156,185,186

* 电信:133,1349,153,180,189,181

* 新增:14_,17_

*/

NSString * MOBIL = @"^1(3[0-9]|4[0-9]|5[0-35-9]|7[0-9]|8[025-9])\\d{8}$";

/**

10        * 中国移动:China Mobile

11        * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188

12        */

NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[2378])\\d)\\d{7}$";

/**

15        * 中国联通:China Unicom

16        * 130,131,132,152,155,156,185,186

17        */

NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";

/**

20        * 中国电信:China Telecom

21        * 133,1349,153,180,189,181(增加)

22        */

NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";

/**

25        * 大陆地区固话及小灵通

26        * 区号:010,020,021,022,023,024,025,027,028,029

27        * 号码:七位或八位

28        */

// NSString * PHS = @"^0(10|2[0-5789]|\\d{3})\\d{7,8}$";

NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBIL];

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]

|| [regextestcm evaluateWithObject:mobileNum]

|| [regextestct evaluateWithObject:mobileNum]

|| [regextestcu evaluateWithObject:mobileNum])) {

return YES;

}

return NO;

}

```

### 密码正则判断6-16 大小写数字

```

+ (BOOL) isPassword:(NSString *)password;

{

NSRegularExpression *regularexpression = [[NSRegularExpression alloc]

initWithPattern:@"^[a-zA-Z0-9]{6,16}$"

options:NSRegularExpressionCaseInsensitive

error:nil];

NSUInteger numberofMatch = [regularexpression numberOfMatchesInString:password

options:NSMatchingReportProgress

range:NSMakeRange(0, password.length)];

if(numberofMatch > 0)

return YES;

return NO;

```

### 邮箱的正则判断

```

+ (BOOL) isEmail:(NSString *)email

{

NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

if ([emailTest evaluateWithObject:email]) {

return YES;

}

return NO;

}

```

### 身份证正则判断

```

+ (BOOL) isIdentityCard: (NSString *)identityCard

{

NSString *idnum = @"^(\\d{14}|\\d{17})(\\d|[xX])$";

NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",idnum];

return [identityCardPredicate evaluateWithObject:identityCard];

}

```

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,390评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,821评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,632评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,170评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,033评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,098评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,511评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,204评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,479评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,572评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,341评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,893评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,171评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,486评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,676评论 2 335

推荐阅读更多精彩内容