• iOS -一些常用的方法


    1、获取本地的语言

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


    2、获取Mac地址

    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 ");  
    27.         return NULL;  
    28.     }  
    29.       
    30.     if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0)  
    31.     {  
    32.         printf("Error: sysctl, take 1 ");  
    33.         return NULL;  
    34.     }  
    35.       
    36.     if ((buf = malloc(len)) == NULL)  
    37.     {  
    38.         printf("Could not allocate memory. error! ");  
    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、微博中获取时间差,(几天前,几小时前,几分钟前)

    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、计算字符串中单词的个数

    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、屏幕截图并保存到相册

    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、获取本月,本周,本季度第一天的时间戳

    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、判断是否越狱

     

    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、定义单例的宏

     

    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、网络状态检测

     

    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、添加推送消息

     

    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

      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. }  
  • 相关阅读:
    第四章 利用函数实现指定的功能
    5-7 点到原点的距离(多态)
    5-2 宠物的生长(多态)
    5-7 学生cpp成绩统计
    5-6 学生CPP成绩计算
    php将远程图片下载保存到本地
    vs2010 调试快捷键
    vs2010 快捷键大全
    [C#] 使用Application.AddMessageFilter当做Form的热键
    C# 收发和处理自定义的WINDOWS消息
  • 原文地址:https://www.cnblogs.com/guangleijia/p/4930285.html
Copyright © 2020-2023  润新知