OC常用方法總結 不定期更新

搶手的哥發表於2017-12-14

1.統一收起鍵盤

[[[UIApplication sharedApplication] keyWindow] endEditing:YES];
複製程式碼

2.陣列去重

NSArray *newArr = [oldArr valueForKeyPath:@“@distinctUnionOfObjects.self"];
@distinctUnionOfObjects.self  表示比較物件
@distinctUnionOfObjects.[key] 表示比較物件的任意keyboarded
複製程式碼

3.修改textField的placeholder的字型顏色、大小

[textField setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
[textField setValue:[UIFont boldSystemFontOfSize:16] forKeyPath:@"_placeholderLabel.font"];
複製程式碼

4.給一個view截圖

UIGraphicsBeginImageContextWithOptions(view.bounds.size, YES, 0.0);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
複製程式碼

5.UIView背景顏色漸變

UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
[self.view addSubview:view];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
複製程式碼

6.為UIView某個角新增圓角

// 左上角和右下角新增圓角
UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:view.bounds byRoundingCorners:(UIRectCornerTopLeft | UIRectCornerBottomRight) cornerRadii:CGSizeMake(20, 20)];
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = view.bounds;
maskLayer.path = maskPath.CGPath;
view.layer.mask = maskLayer;
複製程式碼

7.拿到當前正在顯示的控制器

- (UIViewController *)getVisibleViewControllerFrom:(UIViewController*)vc {
    if ([vc isKindOfClass:[UINavigationController class]]) {
        return [self getVisibleViewControllerFrom:[((UINavigationController*) vc) visibleViewController]];
    }else if ([vc isKindOfClass:[UITabBarController class]]){
        return [self getVisibleViewControllerFrom:[((UITabBarController*) vc) selectedViewController]];
    } else {
        if (vc.presentedViewController) {
            return [self getVisibleViewControllerFrom:vc.presentedViewController];
        } else {
            return vc;
        }
    }
}
複製程式碼

8.tableViewCell分割線頂到頭

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    [cell setSeparatorInset:UIEdgeInsetsZero];
    [cell setLayoutMargins:UIEdgeInsetsZero];
    cell.preservesSuperviewLayoutMargins = NO;
}
- (void)viewDidLayoutSubviews {
    [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    [self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
複製程式碼

9.image新增倒影效果

- (void)setImageShadow {
    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];
}
複製程式碼

10.新增圖片水印

// 畫水印
- (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;
}
複製程式碼

11.刪除NSUserDefaults所有記錄

//方法一
NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
[[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];  
//方法二  
- (void)resetDefaults {   
  NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
     NSDictionary * dict = [defs dictionaryRepresentation];
     for (id key in dict) {
          [defs removeObjectForKey:key];
     }
      [defs synchronize];
 }
// 方法三
[[NSUserDefaults standardUserDefaults] setPersistentDomain:[NSDictionary dictionary] forName:[[NSBundle mainBundle] bundleIdentifier]];
複製程式碼

12.跳進app許可權設定

if (UIApplicationOpenSettingsURLString != NULL) {
    NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    [[UIApplication sharedApplication] openURL:url];
}
複製程式碼

13.獲取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 in enumerator) {
        NSString *path = [myCachePath stringByAppendingPathComponent:fileName];
        NSDictionary *fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:nil];
        //自定義所有快取大小
        count += fileDict.fileSize;
    }
    // 得到是位元組  轉化為M
    CGFloat totalSize = ((CGFloat)imageCacheSize+count)/1024/1024;
    return totalSize;
}
複製程式碼

14.清理app快取

- (void)cleanAppCache {
    // 刪除兩部分
    // 1.刪除 sd 圖片快取
    // 先清除記憶體中的圖片快取
    [[SDImageCache sharedImageCache] clearMemory];
    // 清除磁碟的快取
    [[SDImageCache sharedImageCache] clearDisk];
    // 2.刪除自己快取
    NSString *myCachePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    [[NSFileManager defaultManager] removeItemAtPath:myCachePath error:nil];
}
複製程式碼

15.幾個常用許可權判斷

- (void)checkAppAuthorization{
    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(@"沒有相簿許可權");
        }
    }];
}

複製程式碼

16.文字生成二維碼

/**
 生成二維碼

 @param codeString 二維碼客串
 @return 二維碼圖片
 */
+ (UIImage *)qrCodeWithString:(NSString *)codeString{
    
    // 1.建立過濾器
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    // 2.恢復預設
    [filter setDefaults];
    // 3.給過濾器新增資料(正規表示式/賬號和密碼)
    NSString *dataString = codeString;
    NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
    [filter setValue:data forKeyPath:@"inputMessage"];
    // 4.獲取輸出的二維碼
    CIImage *outputImage = [filter outputImage];
    // 5.將CIImage轉換成UIImage,並放大顯示
    return [self createNonInterpolatedUIImageFormCIImage:outputImage withSize:400];
}

/**
 根據CIImage生成指定大小的UIImage
 
 @param image CIImage
 @param size 圖片寬度
 */
+ (UIImage *)createNonInterpolatedUIImageFormCIImage:(CIImage *)image withSize:(CGFloat)size {
    
    CGRect extent = CGRectIntegral(image.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    // 1.建立bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:image fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 2.儲存bitmap到圖片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}
複製程式碼

17.手機號碼驗證

/**
 *  手機號碼驗證
 *
 *  @param mobileNum 手機號
 *
 *  @return 是否
 */
+ (BOOL)isMobileNumber:(NSString *)mobileNum {
    
    if (mobileNum.length != 11){
        return NO;
    }
    /**
     * 手機號碼:
     * 13[0-9], 14[5,7], 15[0, 1, 2, 3, 5, 6, 7, 8, 9], 17[0, 1, 6, 7, 8], 18[0-9]
     * 移動號段: 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     * 聯通號段: 130,131,132,145,152,155,156,170,171,176,185,186
     * 電訊號段: 133,134,153,170,173,177,180,181,189
     */
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|7[013678]|8[0-9])\\d{8}$";
    /**
     * 中國移動:China Mobile
     * 134,135,136,137,138,139,147,150,151,152,157,158,159,170,178,182,183,184,187,188
     */
    NSString *CM = @"^1(3[4-9]|4[7]|5[0-27-9]|7[08]|8[2-478])\\d{8}$";
    /**
     * 中國聯通:China Unicom
     * 130,131,132,145,152,155,156,170,171,176,185,186
     */
    NSString *CU = @"^1(3[0-2]|4[5]|5[256]|7[016]|8[56])\\d{8}$";
    /**
     * 中國電信:China Telecom
     * 133,134,153,170,173,177,180,181,189
     */
    NSString *CT = @"^1(3[34]|53|7[037]|8[019])\\d{8}$";
    
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    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] == YES)
        || ([regextestcm evaluateWithObject:mobileNum] == YES)
        || ([regextestct evaluateWithObject:mobileNum] == YES)
        || ([regextestcu evaluateWithObject:mobileNum] == YES)){
        
        return YES;
    }
    else{
        return NO;
    }
}

複製程式碼

18.郵箱驗證

/**
 郵箱驗證

 @param email 郵箱地址
 @return 是否
 */
+ (BOOL)isValidateEmail:(NSString *)email {
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

複製程式碼

19.根據年和月返回當月天數

+ (NSInteger)getDaysWithYear:(NSInteger)year
                       month:(NSInteger)month{
                       
    switch (month) {
        case 1:
            return 31;
            break;
        case 2:
            if (year%400==0 || (year%100!=0 && year%4 == 0)) {
                return 29;
            }else{
                return 28;
            }
            break;
        case 3:
            return 31;
            break;
        case 4:
            return 30;
            break;
        case 5:
            return 31;
            break;
        case 6:
            return 30;
            break;
        case 7:
            return 31;
            break;
        case 8:
            return 31;
            break;
        case 9:
            return 30;
            break;
        case 10:
            return 31;
            break;
        case 11:
            return 30;
            break;
        case 12:
            return 31;
            break;
        default:
            return 0;
            break;
    }
}

複製程式碼

20.壓縮圖片成二進位制資料

+ (NSData *)compressImage:(UIImage *)image {
    
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0f);
    if (imageData.length <= 1000*1000) {
        
        return imageData;
    } else if (imageData.length > 1000*1000 && imageData.length < 3000 * 1000) {
        
        imageData = UIImageJPEGRepresentation(image, 0.8f);
        return imageData;
    } else if (imageData.length > 3000*1000 && imageData.length < 5000 * 1000) {
        
        imageData = UIImageJPEGRepresentation(image, 0.6f);
        return imageData;
    } else {
        
        imageData = UIImageJPEGRepresentation(image, 0.4f);
        return imageData;
    }
}
複製程式碼

21.根據正則,過濾特殊字元

/**
 根據正則,過濾特殊字元

 @param regexString 正規表示式
 @return 過濾後的字串
 */
- (NSString *)filterCharactorWithRegex:(NSString *)regexString {
    
    NSString *searchText = self;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:searchText options:NSMatchingReportCompletion range:NSMakeRange(0, searchText.length) withTemplate:@""];
    return result;
}
複製程式碼

22.身份證號碼驗證

/**
 身份證號碼驗證
 * 驗證方法:
 * 1、將前面的身份證號碼17位數分別乘以不同的係數。從第一位到第十七位的係數分別為:7-9-10-5-8-4-2-1-6-3-7-9-10-5-8-4-2
 * 2、將這17位數字和係數相乘的結果相加
 * 3、用加出來和除以11,看餘數是多少?
 * 4、餘數只可能有0-1-2-3-4-5-6-7-8-9-10這11個數字。其分別對應的最後一位身份證的號碼為1-0-X -9-8-7-6-5-4-3-2
 * 5、通過上面得知如果餘數是3,就會在身份證的第18位數字上出現的是9。如果對應的數字是10,身份證的最後一位號碼就是羅馬數字x
 @return 是/否
 */
- (BOOL)isIDCardNumber {
    
    NSInteger sum = 0;
    NSArray *numArr = @[@7, @9, @10, @5, @8, @4, @2, @1, @6, @3, @7, @9, @10, @5, @8, @4, @2]; // 係數
    NSArray *lastArr = @[@"1", @"0", @"X", @"9", @"8",@"7", @"6", @"5", @"4", @"3", @"2"]; // 最後一位身份證的號碼
    
    if (self.length == 15) {
        NSString *lastCharactor =[self substringFromIndex:self.length -1];
        if ([lastCharactor isEqualToString:@"X"] || [lastCharactor isEqualToString:@"x"]) {
            NSString * subStr14 = [self substringToIndex:self.length -1];
            return [self isPureInt:subStr14];
        }else{
            return [self isPureInt:self];
        }
        
    }
    if (self.length == 18) {
        //將字串轉化為大寫
        NSString *newString =[self uppercaseString];
        NSMutableArray *array = [NSMutableArray array];
        for (int i = 0; i < [self length]; i++) {
            [array addObject:[NSString stringWithFormat:@"%C", [newString characterAtIndex:i]]];
        }
        
        for (int i = 0; i < self.length - 1; i++) {
            sum += [array[i] integerValue] * [numArr[i] integerValue];
        }
        return [array[17] isEqualToString:lastArr[sum % 11]];
    }
    
    return NO;
}
複製程式碼

23.判斷字串是否是純數字

/**
 判斷字串是否是純數字
 
 @param string 帶判斷字串
 @return 是/否
 */
- (BOOL)isPureInt:(NSString *)string {
    
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return [scan scanInt:&val] && [scan isAtEnd];
    
}
複製程式碼

24.車牌校驗

/**
 車牌校驗

 @return 是/否
 */
- (BOOL)isCarLicenceNum{

    if (self.length == 7 || self.length == 8) {
        
        NSString *carRegex = @"^[京津滬渝冀豫雲遼黑湘皖魯新蘇浙贛鄂桂甘晉蒙陝吉閩貴粵青藏川寧瓊使領A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9掛學警港澳]{1}$";
        NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
        return [carTest evaluateWithObject:self];
    }else{
        return NO;
    }
}
複製程式碼

25.JSON格式的字串轉換成字典

/*
 * @brief 把格式化的JSON格式的字串轉換成字典
 * @param jsonString JSON格式的字串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    
    if (jsonString == nil) {
        
        return nil;
        
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    
    NSError *err;
    
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    
    if(err) {
        
        NSLog(@"%@json解析失敗:%@",jsonString,err);
        return nil;
        
    }
    return dic;
}
複製程式碼

26.字典轉json格式字串

/**
 *  字典轉json格式字串:
 *
 *  @param NSString <#NSString description#>
 *
 *  @return <#return value description#>
 */

- (NSString*)dictionaryToJson {
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&parseError];
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

複製程式碼

27.通過Value取Key

/**
 通過Value取Key

 @param value ValueString
 @return KeyString
 */
- (NSString *)keyForValue:(NSString *)value {
    
    __block NSString *keyStr = nil;
    [self enumerateKeysAndObjectsUsingBlock:^(NSString * key, id  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([value isEqualToString:obj]) {
            keyStr = key;
            *stop = YES;
        }
    }];
    return keyStr;
}
複製程式碼

28.載入本地json檔案

將本地json檔案,匯入工程,確定target membership勾選上

- (void)loadJson{

    NSError*error;
    //獲取檔案路徑
    NSString *filePath          =[[NSBundle mainBundle] pathForResource:@"test" ofType:@"json"];
    //根據檔案路徑讀取資料
    NSData *jdata               = [[NSData alloc]initWithContentsOfFile:filePath];
    //格式化成json資料
    NSDictionary *jsonObject    = [NSJSONSerialization JSONObjectWithData:jdata options:kNilOptions error:&error];

}
複製程式碼

29.獲取app中所有icon名字陣列


	//獲取app中所有icon名字陣列
    NSDictionary *infoDict  = [[NSBundle mainBundle] infoDictionary];
    NSArray *iconsArr       = infoDict[@"CFBundleIcons"][@"CFBundlePrimaryIcon"][@"CFBundleIconFiles"];
    NSString *iconLastName  = [iconsArr lastObject];
    
複製程式碼

30.計算兩個時間

計算兩個時間字串的時間差

/**
 計算時長
 */
- (NSString *)caculateDurationWithStartTime:(NSString *)startTime andEndTime:(NSString *)endTime{
    if (endTime == nil) {
        return @"未知";
    }
    NSDate *startDate 			= [NSDate date];
    NSDate *endDate 			= [NSDate date];
    
    NSDateFormatter *format 	= [[NSDateFormatter alloc]init];
    format.dateFormat 			= @"YYYY-MM-dd HH:mm:ss";
    format.timeZone				= [NSTimeZone systemTimeZone];
    startDate 					= [format dateFromString:startTime];
    endDate 						= [format dateFromString:endTime];
    NSTimeInterval duration 	= endDate.timeIntervalSince1970 - startDate.timeIntervalSince1970;
    int hour 						= (int)duration / 3600;
    int min 						= (int)duration % 3600 / 60;
    int sec 						= (int)duration % 60;
    
    return [NSString stringWithFormat:@"%d小時%d分%d秒",hour,min,sec];
}

複製程式碼

31.計算兩個NSDate經歷了多少天

/**
 *  返回兩個NSDate經歷了多少天
 */
- (NSInteger)getDaysFrom:(NSDate *)startDate To:(NSDate *)endDate{
    
    NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    [gregorian setFirstWeekday:2];
    
    //去掉時分秒資訊
    NSDate *fromDate;
    NSDate *toDate;
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&fromDate interval:NULL forDate:startDate];
    [gregorian rangeOfUnit:NSCalendarUnitDay startDate:&toDate interval:NULL forDate:endDate];
    NSDateComponents *dayComponents = [gregorian components:NSCalendarUnitDay fromDate:fromDate toDate:toDate options:0];
    
    return dayComponents.day;
}

複製程式碼

32.主動申請常用許可權

記得在info.plist裡面加入對應許可權的描述。

    ///申請麥克風許可權
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
    }];
    ///申請拍照許可權
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
    }];
    ///申請相簿許可權
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
    }];
複製程式碼

相關文章