美文网首页
iOS 一些开发中可能会用到的方法总结,持续更新

iOS 一些开发中可能会用到的方法总结,持续更新

作者: Cary9396 | 来源:发表于2018-06-29 10:40 被阅读0次

    1.判断是否含有非法字符

    + (BOOL)JudgeTheillegalCharacter:(NSString *)content{

        NSString *str =@"^[A-Za-z0-9\\u4e00-\u9fa5]+$";

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

        if (![emailTest evaluateWithObject:content]) {

            return YES;

        }

        return NO;

    }

    2.获取当前的时间

    + (NSString*)getCurrentTimes{

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

        // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制

        [formatter setDateFormat:@"YYYY年MM月dd日"];

        //现在时间,你可以输出来看下是什么格式

        NSDate *datenow = [NSDate date];

        //----------将nsdate按formatter格式转成nsstring

        NSString *currentTimeString = [formatter stringFromDate:datenow];

        NSLog(@"currentTimeString =  %@",currentTimeString);

        return currentTimeString;

    3.手机号码校验

    + (BOOL)checkMobilePhoneNumber:(NSString *)phoneNumber {

        if (xNullString(phoneNumber)) {

            [self alertViewWithMessage:@"号码为空" cancelTitle:@"知道了"];

            return NO;

        }

        if ([phoneNumber containsString:@"appletest"]) {

            return YES;

        }

        NSString *regex = @"^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$";

        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];

        BOOL isMatch = [pred evaluateWithObject:phoneNumber];

        if (!isMatch) {

            [self alertViewWithMessage:@"请输入正确的手机号" cancelTitle:@"知道了"];

            return NO;

        }

        return YES;

    }

    4.判断NSString是否为空

    #define xNullString(string) ((![string isKindOfClass:[NSString class]]) || [string isEqualToString:@""] || (string == nil) || [string isEqualToString:@""] || [string isKindOfClass:[NSNull class]] || [[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0)

    5.获取tabBar  statusBar 高度

    #define xTabBarHeight ([[UIApplication sharedApplication] statusBarFrame].size.height > 20.0f ? 83.0f : 49.0f)

    #define xStatusBarHeight ([[UIApplication sharedApplication] statusBarFrame].size.height)

    6.判断是否为iPhoneX

    #define IS_iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)

    7.禁止手机睡眠

    [UIApplication sharedApplication].idleTimerDisabled = YES;

    8.去除数组中重复的对象

    NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self"];

    9.动画切换window的根控制器

    // options是动画选项

    [UIView transitionWithView:[UIApplication sharedApplication].keyWindow duration:0.5f options:UIViewAnimationOptionTransitionCrossDissolve animations:^{

            BOOL oldState = [UIView areAnimationsEnabled];

            [UIView setAnimationsEnabled:NO];

            [UIApplication sharedApplication].keyWindow.rootViewController = [RootViewController new];

            [UIView setAnimationsEnabled:oldState];

        } completion:^(BOOL finished) {

        }];

    10.设置navigationBar上的title颜色和大小

     [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}]

    11.颜色转图片

    + (UIImage *)cl_imageWithColor:(UIColor *)color {

      CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);

      UIGraphicsBeginImageContext(rect.size);

      CGContextRef context = UIGraphicsGetCurrentContext();

      CGContextSetFillColorWithColor(context, [color CGColor]);

      CGContextFillRect(context, rect);

      UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

      UIGraphicsEndImageContext();

      returnimage;

    }

    12.由角度转换弧度,由弧度转换角度

    #define DegreesToRadian(x) (M_PI * (x) / 180.0)

    #define RadianToDegrees(radian) (radian*180.0)/(M_PI)

    13.自定义NSLog

    #ifdef DEBUG

    #define NSLog(fmt, ...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

    #else

    #define NSLog(...)

    #endif

    14.修改textField的placeholder的字体颜色、大小

    [textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];

    [textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];

    15.将image保存在相册中

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

    或者

    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{

            PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];

            changeRequest.creationDate          = [NSDate date];

        } completionHandler:^(BOOL success, NSError *error) {

            if(success) {

                NSLog(@"successfully saved");

            }

            else{

                NSLog(@"error saving to photos: %@", error);

           }

        }];

    16.获取视频的第一帧图片

     NSURL *url = [NSURL URLWithString:filepath];

        AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:url options:nil];

        AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];

        generate1.appliesPreferredTrackTransform = YES;

        NSError *err = NULL;

        CMTime time = CMTimeMake(1, 2);

        CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];

        UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];

        return one;

    17.移除字符串中的空格和换行

    + (NSString *)removeSpaceAndNewline:(NSString *)str {

        NSString *temp = [str stringByReplacingOccurrencesOfString:@" "withString:@""];

        temp = [temp stringByReplacingOccurrencesOfString:@"\r"withString:@""];

        temp = [temp stringByReplacingOccurrencesOfString:@"\n"withString:@""];

        return temp;

    }

    18.身份证号验证

    - (BOOL)validateIdentityCard {

        BOOL flag;

        if(self.length <= 0) {

            flag = NO;

            returnflag;

        }

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

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

        return [identityCardPredicate evaluateWithObject:self];

    }

    19.image圆角

    - (UIImage *)circleImage

    {

        // NO代表透明

        UIGraphicsBeginImageContextWithOptions(self.size, NO, 1);

        // 获得上下文

        CGContextRef ctx = UIGraphicsGetCurrentContext();

        // 添加一个圆

        CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);

        // 方形变圆形

        CGContextAddEllipseInRect(ctx, rect);

        // 裁剪

        CGContextClip(ctx);

        // 将图片画上去

        [self drawInRect:rect];

        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        returnimage;

    }

    20.压缩图片到指定大小

    - (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {

        // Compress by quality

        CGFloat compression = 1;

        NSData *data = UIImageJPEGRepresentation(image, compression);

        if (data.length < maxLength) return image;

        CGFloat max = 1;

        CGFloat min = 0;

        for (int i = 0; i < 6; ++i) {

            compression = (max + min) / 2;

            data = UIImageJPEGRepresentation(image, compression);

            if (data.length < maxLength * 0.9) {

                min = compression;

            } else if (data.length > maxLength) {

                max = compression;

            } else {

                break;

            }

        }

        UIImage *resultImage = [UIImage imageWithData:data];

        if (data.length < maxLength) return resultImage;

        // Compress by size

        NSUInteger lastDataLength = 0;

        while (data.length > maxLength && data.length != lastDataLength) {

            lastDataLength = data.length;

            CGFloat ratio = (CGFloat)maxLength / data.length;

            CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),

                                    (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank

            UIGraphicsBeginImageContext(size);

            [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

            resultImage = UIGraphicsGetImageFromCurrentImageContext();

            UIGraphicsEndImageContext();

            data = UIImageJPEGRepresentation(resultImage, compression);

        }

        return resultImage;

    }

    21.设置navigationBar上的title颜色和大小

     [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName : [UIColor youColor], NSFontAttributeName : [UIFont systemFontOfSize:15]}];

    22.获取app缓存大小

    - (CGFloat)getCachSize {

        NSUInteger imageCacheSize = [[SDImageCache sharedImageCache] getSize];

        //获取自定义缓存大小

        //用枚举器遍历 一个文件夹的内容

        //1.获取 文件夹枚举器

        NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];

        NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:myCachePath];

        __block NSUInteger count = 0;

        //2.遍历

        for(NSString *fileName inenumerator) {

            NSString *path = [myCachePath stringByAppendingPathComponent:fileName];

            NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];

            count += fileDict.fileSize;//自定义所有缓存大小

        }

        // 得到是字节  转化为M

        CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;

        returntotalSize;

    }

    23.几个常用权限判断

     if([CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied) {

            NSLog(@"没有定位权限");

        }

        AVAuthorizationStatus statusVideo = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];

        if(statusVideo == AVAuthorizationStatusDenied) {

            NSLog(@"没有摄像头权限");

        }

        //是否有麦克风权限

        AVAuthorizationStatus statusAudio = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];

        if(statusAudio == AVAuthorizationStatusDenied) {

            NSLog(@"没有录音权限");

        }

        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

            if(status == PHAuthorizationStatusDenied) {

                NSLog(@"没有相册权限");

            }

        }];

    24.判断图片类型

    //通过图片Data数据第一个字节 来获取图片扩展名

    - (NSString *)contentTypeForImageData:(NSData *)data

    {

        uint8_t c;

        [data getBytes:&c length:1];

        switch(c)

        {

            case0xFF:

                return @"jpeg";

            case0x89:

                return @"png";

            case0x47:

                return @"gif";

            case0x49:

            case0x4D:

                return@"tiff";

            case0x52:

            if([data length] < 12) {

                return nil;

            }

            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];

            if([testString hasPrefix:@"RIFF"]

                && [testString hasSuffix:@"WEBP"])

            {

                return@"webp";

            }

            return nil;

        }

        return nil;

    }

    25.获取手机和app信息

    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  

     CFShow(infoDictionary);  

    // app名称  

     NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];  

     // app版本  

     NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  

     // app build版本  

     NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];  

        //手机序列号  

        NSString* identifierNumber = [[UIDevice currentDevice] uniqueIdentifier];  

        NSLog(@"手机序列号: %@",identifierNumber);  

        //手机别名: 用户定义的名称  

        NSString* userPhoneName = [[UIDevice currentDevice] name];  

        NSLog(@"手机别名: %@", userPhoneName);  

        //设备名称  

        NSString* deviceName = [[UIDevice currentDevice] systemName];  

        NSLog(@"设备名称: %@",deviceName );  

        //手机系统版本  

        NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];  

        NSLog(@"手机系统版本: %@", phoneVersion);  

        //手机型号  

        NSString* phoneModel = [[UIDevice currentDevice] model];  

        NSLog(@"手机型号: %@",phoneModel );  

        //地方型号  (国际化区域名称)  

        NSString* localPhoneModel = [[UIDevice currentDevice] localizedModel];  

        NSLog(@"国际化区域名称: %@",localPhoneModel );  

        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];  

        // 当前应用名称  

        NSString *appCurName = [infoDictionary objectForKey:@"CFBundleDisplayName"];  

        NSLog(@"当前应用名称:%@",appCurName);  

        // 当前应用软件版本  比如:1.0.1  

        NSString *appCurVersion = [infoDictionary objectForKey:@"CFBundleShortVersionString"];  

        NSLog(@"当前应用软件版本:%@",appCurVersion);  

        // 当前应用版本号码   int类型  

        NSString *appCurVersionNum = [infoDictionary objectForKey:@"CFBundleVersion"];  

        NSLog(@"当前应用版本号码:%@",appCurVersionNum);

    26.获取一个类的所有属性

    id LenderClass = objc_getClass("Lender");

    unsigned int outCount, i;

    objc_property_t *properties = class_copyPropertyList(LenderClass, &outCount);

    for(i = 0; i < outCount; i++) {

        objc_property_t property = properties[i];

        fprintf(stdout, "%s %s\n", property_getName(property), property_getAttributes(property));

    }

    27.获得灰度图

    + (UIImage*)covertToGrayImageFromImage:(UIImage*)sourceImage

    {

        int width = sourceImage.size.width;

        int height = sourceImage.size.height;

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();

        CGContextRef context = CGBitmapContextCreate (nil,width,height,8,0,colorSpace,kCGImageAlphaNone);

        CGColorSpaceRelease(colorSpace);

        if(context == NULL) {

            return nil;

        }

        CGContextDrawImage(context,CGRectMake(0, 0, width, height), sourceImage.CGImage);

        CGImageRef contextRef = CGBitmapContextCreateImage(context);

        UIImage *grayImage = [UIImage imageWithCGImage:contextRef];

        CGContextRelease(context);

        CGImageRelease(contextRef);

        return grayImage;

    }

    28.为imageView添加倒影

        CGRect frame = self.frame;

        frame.origin.y += (frame.size.height + 1);

        UIImageView *reflectionImageView = [[UIImageView alloc] initWithFrame:frame];

        self.clipsToBounds = TRUE;

        reflectionImageView.contentMode = self.contentMode;

        [reflectionImageView setImage:self.image];

        reflectionImageView.transform = CGAffineTransformMakeScale(1.0, -1.0);

        CALayer *reflectionLayer = [reflectionImageView layer];

        CAGradientLayer *gradientLayer = [CAGradientLayer layer];

        gradientLayer.bounds = reflectionLayer.bounds;

        gradientLayer.position = CGPointMake(reflectionLayer.bounds.size.width / 2, reflectionLayer.bounds.size.height * 0.5);

        gradientLayer.colors = [NSArray arrayWithObjects:

                                (id)[[UIColor clearColor] CGColor],

                                (id)[[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] CGColor], nil];

        gradientLayer.startPoint = CGPointMake(0.5,0.5);

        gradientLayer.endPoint = CGPointMake(0.5,1.0);

        reflectionLayer.mask = gradientLayer;

        [self.superview addSubview:reflectionImageView];

    29.画水印

    // 画水印

    - (void) setImage:(UIImage *)image withWaterMark:(UIImage *)mark inRect:(CGRect)rect

    {

        if([[[UIDevice currentDevice] systemVersion] floatValue] >= 4.0)

        {

            UIGraphicsBeginImageContextWithOptions(self.frame.size, NO, 0.0);

        }

        //原图

        [image drawInRect:self.bounds];

        //水印图

        [mark drawInRect:rect];

        UIImage *newPic = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        self.image = newPic;

    }

    30.获取视频的时长

    + (NSInteger)getVideoTimeByUrlString:(NSString *)urlString {

        NSURL *videoUrl = [NSURL URLWithString:urlString];

        AVURLAsset *avUrl = [AVURLAsset assetWithURL:videoUrl];

        CMTime time = [avUrl duration];

        int seconds = ceil(time.value/time.timescale);

        returnseconds;

    }

    31.UILabel设置内边距

    //子类化UILabel,重写drawTextInRect方法

    - (void)drawTextInRect:(CGRect)rect {

        // 边距,上左下右

        UIEdgeInsets insets = {0, 5, 0, 5};

        [superdrawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];

    }

    32.UILabel设置文字描边

    //子类化UILabel,重写drawTextInRect方法

    - (void)drawTextInRect:(CGRect)rect

    {

        CGContextRef c = UIGraphicsGetCurrentContext();

        // 设置描边宽度

        CGContextSetLineWidth(c, 1);

        CGContextSetLineJoin(c, kCGLineJoinRound);

        CGContextSetTextDrawingMode(c, kCGTextStroke);

        // 描边颜色

        self.textColor = [UIColor redColor];

        [superdrawTextInRect:rect];

        // 文本颜色

        self.textColor = [UIColor yellowColor];

        CGContextSetTextDrawingMode(c, kCGTextFill);

        [superdrawTextInRect:rect];

    }

    33.压缩图片到指定尺寸

    - (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize{

        // Create a graphics image context

        UIGraphicsBeginImageContext(newSize);

        // Tell the old image to draw in this new context, with the desired

        // new size

        [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

        // Get the new image from the context

        UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

        // End the context

        UIGraphicsEndImageContext();

        // Return the new image.

        return newImage;

    }

    34.压缩图片到指定大小

    - (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {

        CGFloat compression = 1;

        NSData *data = UIImageJPEGRepresentation(image, compression);

        if (data.length < maxLength) return image;

        CGFloat max = 1;

        CGFloat min = 0;

        for (int i = 0; i < 6; ++i) {

            compression = (max + min) / 2;

            data = UIImageJPEGRepresentation(image, compression);

            if (data.length < maxLength * 0.9) {

                min = compression;

            } else if (data.length > maxLength) {

                max = compression;

            } else {

                break;

            }

        }

        UIImage *resultImage = [UIImage imageWithData:data];

        if (data.length < maxLength) return resultImage;

        NSUInteger lastDataLength = 0;

        while (data.length > maxLength && data.length != lastDataLength) {

            lastDataLength = data.length;

            CGFloat ratio = (CGFloat)maxLength / data.length;

            CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),

                                    (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank

            UIGraphicsBeginImageContext(size);

            [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];

            resultImage = UIGraphicsGetImageFromCurrentImageContext();

            UIGraphicsEndImageContext();

            data = UIImageJPEGRepresentation(resultImage, compression);

        }

        return resultImage;

    }

    34. 获取 wlan 的 macIP

    + (NSString*)getWLANMacIP {

        NSString*ssid =@"Not Found";

        NSString*macIp =@"Not Found";

        CFArrayRef myArray = CNCopySupportedInterfaces();

        if(myArray !=nil) {

            CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));

            if(myDict !=nil) {

                NSDictionary*dict = (NSDictionary*)CFBridgingRelease(myDict);

                ssid = [dict valueForKey:@"SSID"];

                macIp = [dic valueForKey:@"BSSID"];

            }    }

        NSLog(@"ssid: %@", ssid);

        return  macIp;

    }

    35.获取字符串宽度

    + (CGFloat)getWidthString:(NSString*)wString font:(UIFont*)fFont {

        NSDictionary *fontDic = @{NSFontAttributeName:fFont};

        CGRect rect = [wString boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, 0.0f) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];

        return  ceilf(rect.size.width);

    }

    36. 获取字符串高度

    + (CGFloat)getHeightString:(NSString*)hString font:(UIFont*)font width:(CGFloat)width {

        NSDictionary *fontDic = @{NSFontAttributeName : font};

        CGRect contentRect = [hString boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingUsesLineFragmentOrigin attributes:fontDic context:nil];

        return   ceilf(contentRect.size.height);

    }

    37.改变图片的透明度

    + (UIImage*)imageByApplyingAlpha:(CGFloat)alpha image:(UIImage*)image {

        UIGraphicsBeginImageContextWithOptions(image.size, NO, 0.0f);

        CGContextRef ctx = UIGraphicsGetCurrentContext();

        CGRectarea =CGRectMake(0,0, image.size.width, image.size.height);

        CGContextScaleCTM(ctx, 1, -1);

        CGContextTranslateCTM(ctx, 0, -area.size.height);

        CGContextSetBlendMode(ctx, kCGBlendModeMultiply);

        CGContextSetAlpha(ctx, alpha);

        CGContextDrawImage(ctx, area, image.CGImage);

        UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();

        UIGraphicsEndImageContext();

        return   newImage;

    }

    38.获取手机的运营商

    + (NSString*)operator{

        //获取本机运营商名称

        CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];

        CTCarrier *carrier = [info subscriberCellularProvider];

        //当前手机所属运营商名称

        NSString*mobile;

        //先判断有没有SIM卡,如果没有则不获取本机运营商

        if(!carrier.isoCountryCode) {

            CLLog(@"没有SIM卡");

            mobile =@"无运营商";

        }else{

            mobile = [carriercarrierName];

        }

        return mobile;

    }

    39.震动反馈(iOS10以后)

    UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleMedium];

    [feedBackGenertor impactOccurred];

    40.震动加音效

    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

    41.汉语转拼音

    + (NSString*)getPinYinFromString:(NSString*)string{

    CFMutableStringRef aCstring = CFStringCreateMutableCopy(NULL, 0, (__bridge_retained CFStringRef)string);

        /**

         *  创建可变CFString

         *

         *  @paramNULL 使用默认创建器

         *  @param0    长度不限制

         *  @param"张三" cf字串

         *

         *  @return可变字符串

         */

    /**

     *  1. string: 要转换的字符串(可变的)

     2. range: 要转换的范围 NULL全转换

     3. transform: 指定要怎样的转换

     4. reverse: 是否可逆的转换

     */

    CFStringTransform(aCstring, NULL, kCFStringTransformMandarinLatin, NO);

    CFStringTransform(aCstring, NULL, kCFStringTransformStripDiacritics, NO);

    NSLog(@"%@",aCstring);

    return [NSString stringWithFormat:@"%@",aCstring];

    }

    42.判断字符串是否以字母开头

    - (BOOL)isEnglishFirst:(NSString *)str {

        NSString *regular = @"^[A-Za-z].+$";

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regular];

        if ([predicate evaluateWithObject:str] == YES){

            return YES;

        }else{

            return NO;

        }

    43.判断字符串是否以汉字开头

    - (BOOL)isChineseFirst:(NSString *)str {

        int utfCode = 0;

        void *buffer = &utfCode;

        NSRange range = NSMakeRange(0, 1);

        BOOL b = [str getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];

        if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5)){

            return YES;

        }else{

            return NO;

        }

    相关文章

      网友评论

          本文标题:iOS 一些开发中可能会用到的方法总结,持续更新

          本文链接:https://www.haomeiwen.com/subject/xyogyftx.html