美文网首页
OC 常用的公共方法

OC 常用的公共方法

作者: MacPen | 来源:发表于2017-12-21 14:15 被阅读6次

    整理下作为笔记,能够给需要的同学提供帮助则更好。

    1.计算总磁盘空间(单位mb)
    - (float)diskSize {
        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.计算磁盘可用空间(单位mb)
    - (float)diskFreeSize {
        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;
    }
    
    3.计算文件大小(单位byte)
    - (float)fileSize {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"sf_muni" ofType:@"pdf"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if (![fileManager fileExistsAtPath:path])
            return 0;
        return [[fileManager attributesOfItemAtPath:path error:nil] fileSize];
    }
    
    4.获取字符串首字母(字符或汉字都可以)
    - (NSString *)firstCharacterWithString:(NSString *)string {
        NSMutableString *str = [NSMutableString stringWithString:string];
        CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
        CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
        NSString *pingyin = [str capitalizedString];
        return [pingyin substringToIndex:1];
    }
    
    5.对数组中的元素按首字母分组排序
    - (NSDictionary *)dictionaryOrderByCharacterWithOriginalArray:(NSArray *)array{
        if (array.count == 0) {
            return nil;
        }
        for (id obj in array) {
            if (![obj isKindOfClass:[NSString class]]) {
                return nil;
            }
        }
        UILocalizedIndexedCollation *indexedCollation = [UILocalizedIndexedCollation 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;
    }
    //获取字符串(或汉字)首字母
    - (NSString *)firstCharacterWithString:(NSString *)string{
        NSMutableString *str = [NSMutableString stringWithString:string];
        CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformMandarinLatin, NO);
        CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
        NSString *pingyin = [str capitalizedString];
        return [pingyin substringToIndex:1];
    }
    
    6.获取当前时间
    //NSString *format = @"yyyy-MM-dd HH:mm:ss" 或 @"yyyy年MM月dd日 HH时mm分ss秒"
    - (NSString *)currentDateWithFormat:(NSString *)format{
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:format];
        return [dateFormatter stringFromDate:[NSDate date]];
    }
    
    7.十六进制颜色码转为UIColor对象
    - (UIColor *)colorWithHexString:(NSString *)color{
        NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
        // String should be 6 or 8 characters
        if ([cString length] < 6) {
            return [UIColor clearColor];
        }
        // strip "0X" or "#" if it appears
        if ([cString hasPrefix:@"0X"])
            cString = [cString substringFromIndex:2];
        if ([cString hasPrefix:@"#"])
            cString = [cString substringFromIndex:1];
        if ([cString length] != 6)
            return [UIColor clearColor];
        // Separate into r, g, b substrings
        NSRange range;
        range.location = 0;
        range.length = 2;
        //r
        NSString *rString = [cString substringWithRange:range];
        //g
        range.location = 2;
        NSString *gString = [cString substringWithRange:range];
        //b
        range.location = 4;
        NSString *bString = [cString substringWithRange:range];
        // Scan values
        unsigned int r, g, b;
        [[NSScanner scannerWithString:rString] scanHexInt:&r];
        [[NSScanner scannerWithString:gString] scanHexInt:&g];
        [[NSScanner scannerWithString:bString] scanHexInt:&b];
        return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
    }
    
    8.图片加滤镜
       //filterName
        // 怀旧 --> CIPhotoEffectInstant              单色 --> CIPhotoEffectMono
        // 黑白 --> CIPhotoEffectNoir                 褪色 --> CIPhotoEffectFade
        // 色调 --> CIPhotoEffectTonal                冲印 --> CIPhotoEffectProcess
        // 岁月 --> CIPhotoEffectTransfer             铬黄 --> CIPhotoEffectChrome
    - (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;
    }
    
    9.图片模糊处理
       //blurName
        // 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;
        }
    }
    
    10.全屏截图
    - (UIImage *)shotScreen{
        UIWindow *window = [UIApplication sharedApplication].keyWindow;
        UIGraphicsBeginImageContext(window.bounds.size);
        [window.layer renderInContext:UIGraphicsGetCurrentContext()];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
    }
    
    11.获取IP地址
    #import <ifaddrs.h>
    #import <arpa/inet.h>
    
    - (NSString *)getIPAddress {
        NSString *address = @"error";
        struct ifaddrs *interfaces = NULL;
        struct ifaddrs *temp_addr = NULL;
        int success = 0;
        success = getifaddrs(&interfaces);
        if (success == 0) {
            temp_addr = interfaces;
            while(temp_addr != NULL) {
                if(temp_addr->ifa_addr->sa_family == AF_INET) {
                    if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                        address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                    }
                }
                temp_addr = temp_addr->ifa_next;
            }
        }
        freeifaddrs(interfaces);
        return address;
    }
    
    12.判断字符串中是否有中文
    - (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;
    }
    
    13.判断字符串是否为纯数字
    - (BOOL)isAllNum:(NSString *)string{
        unichar c;
        for (int i=0; i<string.length; i++) {
            c=[string characterAtIndex:i];
            if (!isdigit(c)) {
                return NO;
            }
        }
        return YES;
    }
    
    14.计算文本高度
    - (float)calculateHeightWithContent:(NSString *)content andWidth:(float)width andFontSize:(float)fontSize {
        //初始值,宽度给定值,高度给最大值
        CGSize size = CGSizeMake(width,2000);
        //设置字体大小
        NSDictionary *attributes = @{NSFontAttributeName:[UIFont systemFontOfSize:fontSize]};
        //计算尺寸
        CGRect summaryRect = [content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:attributes        context:nil];
        return summaryRect.size.height;
    }
    
    15.获取指定UITableViewCell在屏幕上的实际位置
    - (CGRect)cellRectInWindow:(NSIndexPath *)index {
        CGRect rectInTableView = [self.tableView rectForRowAtIndexPath:index];
        return [self.tableView convertRect:rectInTableView toView:[self.tableView superview]];
    }
    

    相关文章

      网友评论

          本文标题:OC 常用的公共方法

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