【我就看看不说话】常用函数

2024-08-27 07:58
文章标签 函数 常用 看看 说话

本文主要是介绍【我就看看不说话】常用函数,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、获取本地的语言

[cpp]  view plain copy
  1. + (NSString *)getLocalLanguage  
  2. {  
  3.     NSString *language = [[[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"] objectAtIndex:0];  
  4.     return language;  
  5. }  

2、获取Mac地址

[cpp]  view plain copy
  1. // returns the local MAC address.  
  2. + (NSString*) macAddress:(NSString*)interfaceNameOrNil  
  3. {  
  4.     // uses en0 as the default interface name  
  5.     NSString* interfaceName = interfaceNameOrNil;  
  6.     if (interfaceName == nil)  
  7.     {  
  8.         interfaceName = @"en0";  
  9.     }  
  10.       
  11.     int                 mib[6];  
  12.     size_t              len;  
  13.     char                *buf;  
  14.     unsigned char       *ptr;  
  15.     struct if_msghdr    *ifm;  
  16.     struct sockaddr_dl  *sdl;  
  17.       
  18.     mib[0] = CTL_NET;  
  19.     mib[1] = AF_ROUTE;  
  20.     mib[2] = 0;  
  21.     mib[3] = AF_LINK;  
  22.     mib[4] = NET_RT_IFLIST;  
  23.       
  24.     if ((mib[5] = if_nametoindex([interfaceName UTF8String])) == 0)  
  25.     {  
  26.         printf("Error: if_nametoindex error\n");  
  27.         return NULL;  
  28.     }  
  29.       
  30.     if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)  
  31.     {  
  32.         printf("Error: sysctl, take 1\n");  
  33.         return NULL;  
  34.     }  
  35.       
  36.     if ((buf = malloc(len)) == NULL)  
  37.     {  
  38.         printf("Could not allocate memory. error!\n");  
  39.         return NULL;  
  40.     }  
  41.       
  42.     if (sysctl(mib, 6, buf, &len, NULL, 0) < 0)  
  43.     {  
  44.         printf("Error: sysctl, take 2");  
  45.         free(buf);  
  46.         return NULL;  
  47.     }  
  48.       
  49.     ifm = (struct if_msghdr*) buf;  
  50.     sdl = (struct sockaddr_dl*) (ifm + 1);  
  51.     ptr = (unsigned char*) LLADDR(sdl);  
  52.     NSString *outstring = [NSString stringWithFormat:@"%02X:%02X:%02X:%02X:%02X:%02X",  
  53.                            *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];  
  54.     free(buf);  
  55.       
  56.     return outstring;  
  57. }  

3、微博中获取时间差,(几天前,几小时前,几分钟前)

[cpp]  view plain copy
  1. + (NSString *) getTimeDiffString:(NSTimeInterval) timestamp  
  2. {  
  3.   
  4.     NSCalendar *cal = [NSCalendar currentCalendar];  
  5.     NSDate *todate = [NSDate dateWithTimeIntervalSince1970:timestamp];  
  6.     NSDate *today = [NSDate date];//当前时间  
  7.     unsigned int unitFlag = NSDayCalendarUnit | NSHourCalendarUnit |NSMinuteCalendarUnit;  
  8.     NSDateComponents *gap = [cal components:unitFlag fromDate:today toDate:todate options:0];//计算时间差  
  9.      
  10.     if (ABS([gap day]) > 0)  
  11.     {  
  12.         return [NSString stringWithFormat:@"%d天前", ABS([gap day])];  
  13.     }else if(ABS([gap hour]) > 0)  
  14.     {  
  15.         return [NSString stringWithFormat:@"%d小时前", ABS([gap hour])];  
  16.     }else   
  17.     {  
  18.         return [NSString stringWithFormat:@"%d分钟前",  ABS([gap minute])];  
  19.     }  
  20. }  

4、计算字符串中单词的个数

[cpp]  view plain copy
  1. + (int)countWords:(NSString*)s  
  2. {  
  3.     int i,n=[s length],l=0,a=0,b=0;  
  4.     unichar c;  
  5.     for(i=0;i<n;i++){  
  6.         c=[s characterAtIndex:i];  
  7.         if(isblank(c))  
  8.         {  
  9.             b++;  
  10.         }else if(isascii(c))  
  11.         {  
  12.             a++;  
  13.         }else  
  14.         {  
  15.             l++;  
  16.         }  
  17.     }  
  18.     if(a==0 && l==0)  
  19.     {  
  20.         return 0;  
  21.     }  
  22.     return l+(int)ceilf((float)(a+b)/2.0);  
  23. }  

5、屏幕截图并保存到相册

[cpp]  view plain copy
  1. + (UIImage*)saveImageFromView:(UIView*)view  
  2. {  
  3.     UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, view.layer.contentsScale);  
  4.     [view.layer renderInContext:UIGraphicsGetCurrentContext()];  
  5.     UIImage *image = UIGraphicsGetImageFromCurrentImageContext();  
  6.     UIGraphicsEndImageContext();  
  7.     return image;  
  8. }  
  9.   
  10. + (void)savePhotosAlbum:(UIImage *)image  
  11. {  
  12.     UIImageWriteToSavedPhotosAlbum(image, self, @selector(imageSavedToPhotosAlbum: didFinishSavingWithError: contextInfo:), nil);   
  13. }  
  14.   
  15. + (void)saveImageFromToPhotosAlbum:(UIView*)view  
  16. {  
  17.     UIImage *image = [self saveImageFromView:view];  
  18.     [self savePhotosAlbum:image];  
  19. }  
  20.   
  21. - (void)imageSavedToPhotosAlbum:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *) contextInfo  
  22. {  
  23.     NSString *message;  
  24.     NSString *title;  
  25.     if (!error) {  
  26.         title = @"成功提示";  
  27.         message = @"成功保存到相";  
  28.     } else {  
  29.         title = @"失败提示";  
  30.         message = [error description];  
  31.     }  
  32.     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title  
  33.                                                     message:message  
  34.                                                    delegate:nil  
  35.                                           cancelButtonTitle:@"知道了"  
  36.                                           otherButtonTitles:nil];  
  37.     [alert show];  
  38.     [alert release];  
  39. }  

5、获取本月,本周,本季度第一天的时间戳

[html]  view plain copy
  1. + (unsigned long long)getFirstDayOfWeek:(unsigned long long)timestamp  
  2. {  
  3.     NSDate *now = [NSDate dateWithTimeIntervalSince1970:timestamp];  
  4.     NSCalendar *cal = [NSCalendar currentCalendar];  
  5.     NSDateComponents *comps = [cal  
  6.                                components:NSYearCalendarUnit| NSMonthCalendarUnit| NSWeekCalendarUnit | NSWeekdayCalendarUnit |NSWeekdayOrdinalCalendarUnit  
  7.                                fromDate:now];  
  8.     if (comps.weekday <2)  
  9.     {  
  10.         comps.week = comps.week-1;  
  11.     }  
  12.     comps.weekday = 2;  
  13.     NSDate *firstDay = [cal dateFromComponents:comps];  
  14.     return [firstDay timeIntervalSince1970];  
  15. }  
  16.   
  17. + (unsigned long long)getFirstDayOfQuarter:(unsigned long long)timestamp  
  18. {  
  19.     NSDate *now = [NSDate dateWithTimeIntervalSince1970:timestamp];  
  20.     NSCalendar *cal = [NSCalendar currentCalendar];  
  21.     NSDateComponents *comps = [cal  
  22.                                components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  
  23.                                fromDate:now];  
  24.     if (comps.month <=3)  
  25.     {  
  26.         comps.month =  1;  
  27.     }  
  28.     else if(comps.month<=6)  
  29.     {  
  30.         comps.month =  4;  
  31.     }  
  32.     else if(comps.month<=9)  
  33.     {  
  34.         comps.month =  7;  
  35.     }  
  36.     else if(comps.month<=12)  
  37.     {  
  38.         comps.month =  10;  
  39.     }  
  40.           
  41.     comps.day = 1;  
  42.     NSDate *firstDay = [cal dateFromComponents:comps];  
  43.     return [firstDay timeIntervalSince1970]*1000;  
  44. }  
  45.   
  46. + (unsigned long long)getFirstDayOfMonth:(unsigned long long)timestamp  
  47. {  
  48.     NSDate *now = [NSDate dateWithTimeIntervalSince1970:timestamp/1000];  
  49.     NSCalendar *cal = [NSCalendar currentCalendar];  
  50.     NSDateComponents *comps = [cal  
  51.                                components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit  
  52.                                fromDate:now];  
  53.     comps.day = 1;  
  54.     NSDate *firstDay = [cal dateFromComponents:comps];  
  55.     return [firstDay timeIntervalSince1970]*1000;  
  56. }  

6、判断是否越狱

[cpp]  view plain copy
  1. static const char * __jb_app = NULL;  
  2.   
  3. + (BOOL)isJailBroken  
  4. {  
  5.     static const char * __jb_apps[] =  
  6.     {  
  7.         "/Application/Cydia.app",   
  8.         "/Application/limera1n.app",   
  9.         "/Application/greenpois0n.app",   
  10.         "/Application/blackra1n.app",  
  11.         "/Application/blacksn0w.app",  
  12.         "/Application/redsn0w.app",  
  13.         NULL  
  14.     };  
  15.   
  16.     __jb_app = NULL;  
  17.   
  18.     // method 1  
  19.     for ( int i = 0; __jb_apps[i]; ++i )  
  20.     {  
  21.         if ( [[NSFileManager defaultManager] fileExistsAtPath:[NSString stringWithUTF8String:__jb_apps[i]]] )  
  22.         {  
  23.             __jb_app = __jb_apps[i];  
  24.             return YES;  
  25.         }  
  26.     }  
  27.       
  28.     // method 2  
  29.     if ( [[NSFileManager defaultManager] fileExistsAtPath:@"/private/var/lib/apt/"] )  
  30.     {  
  31.         return YES;  
  32.     }  
  33.       
  34.     // method 3  
  35.     if ( 0 == system("ls") )  
  36.     {  
  37.         return YES;  
  38.     }  
  39.       
  40.     return NO;    
  41. }  
  42.   
  43. + (NSString *)jailBreaker  
  44. {  
  45.     if ( __jb_app )  
  46.     {  
  47.         return [NSString stringWithUTF8String:__jb_app];  
  48.     }  
  49.     else  
  50.     {  
  51.         return @"";  
  52.     }  
  53. }  

7、定义单例的宏

[cpp]  view plain copy
  1. #undef  AS_SINGLETON  
  2. #define AS_SINGLETON( __class ) \  
  3.         + (__class *)sharedInstance;  
  4.   
  5. #undef  DEF_SINGLETON  
  6. #define DEF_SINGLETON( __class ) \  
  7.         + (__class *)sharedInstance \  
  8.         { \  
  9.             static dispatch_once_t once; \  
  10.             static __class * __singleton__; \  
  11.             dispatch_once( &once, ^{ __singleton__ = [[__class alloc] init]; } ); \  
  12.             return __singleton__; \  
  13.         }  

8、网络状态检测

[cpp]  view plain copy
  1. - (void)reachabilityChanged:(NSNotification *)note {  
  2.     Reachability* curReach = [note object];  
  3.     NSParameterAssert([curReach isKindOfClass: [Reachability class]]);  
  4.     NetworkStatus status = [curReach currentReachabilityStatus];  
  5.       
  6.     if (status == NotReachable)  
  7.     {  
  8.           
  9.     }  
  10.     else if(status == kReachableViaWiFi)  
  11.     {  
  12.           
  13.     }  
  14.     else if(status == kReachableViaWWAN)  
  15.     {  
  16.           
  17.     }  
  18.       
  19. }  
  20.   
  21. - (void)setNetworkNotification  
  22. {  
  23.     [[NSNotificationCenter defaultCenter] addObserver:self  
  24.                                              selector:@selector(reachabilityChanged:)  
  25.                                                  name: kReachabilityChangedNotification  
  26.                                                object: nil];  
  27.     _hostReach = [[Reachability reachabilityWithHostName:@"http://www.baidu.com"] retain];  
  28.     [_hostReach startNotifier];  
  29. }  

9、添加推送消息

[cpp]  view plain copy
  1. - (void)setPushNotification  
  2. {  
  3.     [[UIApplication sharedApplication] registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound];  
  4. }  
  5.   
  6.   
  7. - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {  
  8.     NSLog(@"获取设备的deviceToken: %@", deviceToken);  
  9. }  
  10.   
  11. - (void)application:(UIApplication*)application didFailToRegisterForRemoteNotificationsWithError:(NSError*)error{  
  12.       
  13.     NSLog(@"Failed to get token, error: %@", error);  
  14. }  

10、16进制颜色转UIColor

[cpp]  view plain copy
  1. + (UIColor *)colorWithHex:(NSString *)hex {  
  2.     // Remove `#` and `0x`  
  3.     if ([hex hasPrefix:@"#"]) {  
  4.         hex = [hex substringFromIndex:1];  
  5.     } else if ([hex hasPrefix:@"0x"]) {  
  6.         hex = [hex substringFromIndex:2];  
  7.     }  
  8.   
  9.     // Invalid if not 3, 6, or 8 characters  
  10.     NSUInteger length = [hex length];  
  11.     if (length != 3 && length != 6 && length != 8) {  
  12.         return nil;  
  13.     }  
  14.   
  15.     // Make the string 8 characters long for easier parsing  
  16.     if (length == 3) {  
  17.         NSString *r = [hex substringWithRange:NSMakeRange(0, 1)];  
  18.         NSString *g = [hex substringWithRange:NSMakeRange(1, 1)];  
  19.         NSString *b = [hex substringWithRange:NSMakeRange(2, 1)];  
  20.         hex = [NSString stringWithFormat:@"%@%@%@%@%@%@ff",  
  21.                r, r, g, g, b, b];  
  22.     } else if (length == 6) {  
  23.         hex = [hex stringByAppendingString:@"ff"];  
  24.     }  
  25.   
  26.     CGFloat red = [[hex substringWithRange:NSMakeRange(0, 2)] _hexValue] / 255.0f;  
  27.     CGFloat green = [[hex substringWithRange:NSMakeRange(2, 2)] _hexValue] / 255.0f;  
  28.     CGFloat blue = [[hex substringWithRange:NSMakeRange(4, 2)] _hexValue] / 255.0f;  
  29.     CGFloat alpha = [[hex substringWithRange:NSMakeRange(6, 2)] _hexValue] / 255.0f;  
  30.   
  31.     return [UIColor colorWithRed:red green:green blue:blue alpha:alpha];  
  32. }  

这篇关于【我就看看不说话】常用函数的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1111089

相关文章

MySQL 中的 CAST 函数详解及常见用法

《MySQL中的CAST函数详解及常见用法》CAST函数是MySQL中用于数据类型转换的重要函数,它允许你将一个值从一种数据类型转换为另一种数据类型,本文给大家介绍MySQL中的CAST... 目录mysql 中的 CAST 函数详解一、基本语法二、支持的数据类型三、常见用法示例1. 字符串转数字2. 数字

golang中reflect包的常用方法

《golang中reflect包的常用方法》Go反射reflect包提供类型和值方法,用于获取类型信息、访问字段、调用方法等,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值... 目录reflect包方法总结类型 (Type) 方法值 (Value) 方法reflect包方法总结

Python内置函数之classmethod函数使用详解

《Python内置函数之classmethod函数使用详解》:本文主要介绍Python内置函数之classmethod函数使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录1. 类方法定义与基本语法2. 类方法 vs 实例方法 vs 静态方法3. 核心特性与用法(1编程客

C# 比较两个list 之间元素差异的常用方法

《C#比较两个list之间元素差异的常用方法》:本文主要介绍C#比较两个list之间元素差异,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1. 使用Except方法2. 使用Except的逆操作3. 使用LINQ的Join,GroupJoin

Python函数作用域示例详解

《Python函数作用域示例详解》本文介绍了Python中的LEGB作用域规则,详细解析了变量查找的四个层级,通过具体代码示例,展示了各层级的变量访问规则和特性,对python函数作用域相关知识感兴趣... 目录一、LEGB 规则二、作用域实例2.1 局部作用域(Local)2.2 闭包作用域(Enclos

MySQL count()聚合函数详解

《MySQLcount()聚合函数详解》MySQL中的COUNT()函数,它是SQL中最常用的聚合函数之一,用于计算表中符合特定条件的行数,本文给大家介绍MySQLcount()聚合函数,感兴趣的朋... 目录核心功能语法形式重要特性与行为如何选择使用哪种形式?总结深入剖析一下 mysql 中的 COUNT

python常用的正则表达式及作用

《python常用的正则表达式及作用》正则表达式是处理字符串的强大工具,Python通过re模块提供正则表达式支持,本文给大家介绍python常用的正则表达式及作用详解,感兴趣的朋友跟随小编一起看看吧... 目录python常用正则表达式及作用基本匹配模式常用正则表达式示例常用量词边界匹配分组和捕获常用re

MySQL 中 ROW_NUMBER() 函数最佳实践

《MySQL中ROW_NUMBER()函数最佳实践》MySQL中ROW_NUMBER()函数,作为窗口函数为每行分配唯一连续序号,区别于RANK()和DENSE_RANK(),特别适合分页、去重... 目录mysql 中 ROW_NUMBER() 函数详解一、基础语法二、核心特点三、典型应用场景1. 数据分

MySQL数据库的内嵌函数和联合查询实例代码

《MySQL数据库的内嵌函数和联合查询实例代码》联合查询是一种将多个查询结果组合在一起的方法,通常使用UNION、UNIONALL、INTERSECT和EXCEPT关键字,下面:本文主要介绍MyS... 目录一.数据库的内嵌函数1.1聚合函数COUNT([DISTINCT] expr)SUM([DISTIN

Python get()函数用法案例详解

《Pythonget()函数用法案例详解》在Python中,get()是字典(dict)类型的内置方法,用于安全地获取字典中指定键对应的值,它的核心作用是避免因访问不存在的键而引发KeyError错... 目录简介基本语法一、用法二、案例:安全访问未知键三、案例:配置参数默认值简介python是一种高级编