iOS 知識(shí)-常用小技巧大雜燴

  1. 獲取磁盤總空間大小
    <pre>//磁盤總空間
  • (CGFloat)diskOfAllSizeMBytes{
    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;

}

</pre>

  1. 獲取磁盤可用空間大小
    <pre>//磁盤可用空間
  • (CGFloat)diskOfFreeSizeMBytes{
    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;

}

</pre>

  1. 獲取指定路徑下某個(gè)文件的大小
    <pre>//獲取文件大小
  • (long long)fileSizeAtPath:(NSString *)filePath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:filePath]) return 0;
    return [[fileManager attributesOfItemAtPath:filePath error:nil] fileSize];
    }

</pre>

  1. 獲取文件夾下所有文件的大小
    <pre>//獲取文件夾下所有文件的大小
  • (long long)folderSizeAtPath:(NSString *)folderPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *filesEnumerator = [[fileManager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folerSize = 0;
    while ((fileName = [filesEnumerator nextObject]) != nil) {
    NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];
    folerSize += [self fileSizeAtPath:filePath];
    }
    return folerSize;
    }

</pre>

  1. 獲取字符串(或漢字)首字母
    <pre>//獲取字符串(或漢字)首字母
  • (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];
    }

</pre>

  1. 將字符串?dāng)?shù)組按照元素首字母順序進(jìn)行排序分組
    <pre>//將字符串?dāng)?shù)組按照元素首字母順序進(jìn)行排序分組
  • (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];
    //創(chuàng)建27個(gè)分組數(shù)組
    for (int i = 0; i < indexedCollation.sectionTitles.count; i++) {
    NSMutableArray *obj = [NSMutableArray array];
    [objects addObject:obj];
    }
    NSMutableArray *keys = [NSMutableArray arrayWithCapacity:objects.count];
    //按字母順序進(jìn)行分組
    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;
    }
    //去掉空數(shù)組
    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];

</pre>

  1. 獲取當(dāng)前時(shí)間
    <pre>//獲取當(dāng)前時(shí)間
    //format: @"yyyy-MM-dd HH:mm:ss"、@"yyyy年MM月dd日 HH時(shí)mm分ss秒"
  • (NSString *)currentDateWithFormat:(NSString *)format{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    return [dateFormatter stringFromDate:[NSDate date]];
    }

</pre>

  1. 計(jì)算上次日期距離現(xiàn)在多久, 如 xx 小時(shí)前、xx 分鐘前等
    <pre>/**
  • 計(jì)算上次日期距離現(xiàn)在多久
  • @param lastTime 上次日期(需要和格式對(duì)應(yīng))
  • @param format1 上次日期格式
  • @param currentTime 最近日期(需要和格式對(duì)應(yīng))
  • @param format2 最近日期格式
  • @return xx分鐘前、xx小時(shí)前、xx天前
    */
  • (NSString *)timeIntervalFromLastTime:(NSString *)lastTime
    lastTimeFormat:(NSString *)format1
    ToCurrentTime:(NSString *)currentTime
    currentTimeFormat:(NSString *)format2{
    //上次時(shí)間
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //當(dāng)前時(shí)間
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    dateFormatter2.dateFormat = format2;
    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [Utilities timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];
    }

  • (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次時(shí)間
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //當(dāng)前時(shí)間
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //時(shí)間間隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];

    //秒、分、小時(shí)、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;

    if (minutes <= 10) {
    return @"剛剛";
    }else if (minutes < 60){
    return [NSString stringWithFormat: @"%ld分鐘前",(long)minutes];
    }else if (hours < 24){
    return [NSString stringWithFormat: @"%ld小時(shí)前",(long)hours];
    }else if (day < 30){
    return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12){
    NSDateFormatter * df =[[NSDateFormatter alloc]init];
    df.dateFormat = @"M月d日";
    NSString * time = [df stringFromDate:lastDate];
    return time;
    }else if (yers >= 1){
    NSDateFormatter * df =[[NSDateFormatter alloc]init];
    df.dateFormat = @"yyyy年M月d日";
    NSString * time = [df stringFromDate:lastDate];
    return time;
    }
    return @"";
    }

</pre>

  1. 判斷手機(jī)號(hào)碼格式是否正確
    <pre>//判斷手機(jī)號(hào)碼格式是否正確
  • (BOOL)valiMobile:(NSString )mobile{
    mobile = [mobile stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11)
    {
    return NO;
    }else{
    /
    *
    * 移動(dòng)號(hào)段正則表達(dá)式
    /
    NSString CM_NUM = @"^((13[4-9])|(147)|(15[0-2,7-9])|(178)|(18[2-4,7-8]))\d{8}|(1705)\d{7}$";
    /

    * 聯(lián)通號(hào)段正則表達(dá)式
    /
    NSString CU_NUM = @"^((13[0-2])|(145)|(15[5-6])|(176)|(18[5,6]))\d{8}|(1709)\d{7}$";
    /

    * 電信號(hào)段正則表達(dá)式
    */
    NSString *CT_NUM = @"^((133)|(153)|(177)|(18[0,1,9]))\d{8}$";
    NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM_NUM];
    BOOL isMatch1 = [pred1 evaluateWithObject:mobile];
    NSPredicate *pred2 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU_NUM];
    BOOL isMatch2 = [pred2 evaluateWithObject:mobile];
    NSPredicate *pred3 = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT_NUM];
    BOOL isMatch3 = [pred3 evaluateWithObject:mobile];

      if (isMatch1 || isMatch2 || isMatch3) {
          return YES;
      }else{
          return NO;
      }
    

    }
    }

</pre>


  1. 判斷郵箱格式是否正確
    <pre>//利用正則表達(dá)式驗(yàn)證
  • (BOOL)isAvailableEmail:(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];
    }

</pre>

  1. 將十六進(jìn)制顏色轉(zhuǎn)換為 UIColor 對(duì)象
    <pre>//將十六進(jìn)制顏色轉(zhuǎn)換為 UIColor 對(duì)象
  • (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];
    }

</pre>

  1. 對(duì)圖片進(jìn)行濾鏡處理
    <pre>#pragma mark - 對(duì)圖片進(jìn)行濾鏡處理
    // 懷舊 --> CIPhotoEffectInstant 單色 --> CIPhotoEffectMono
    // 黑白 --> CIPhotoEffectNoir 褪色 --> CIPhotoEffectFade
    // 色調(diào) --> CIPhotoEffectTonal 沖印 --> CIPhotoEffectProcess
    // 歲月 --> CIPhotoEffectTransfer 鉻黃 --> CIPhotoEffectChrome
    // CILinearToSRGBToneCurve, CISRGBToneCurveToLinear, CIGaussianBlur, CIBoxBlur, CIDiscBlur, CISepiaTone, CIDepthOfField
  • (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;
    }

</pre>

  1. 對(duì)圖片進(jìn)行模糊處理
    <pre>#pragma mark - 對(duì)圖片進(jìn)行模糊處理
    // CIGaussianBlur ---> 高斯模糊
    // CIBoxBlur ---> 均值模糊(Available in iOS 9.0 and later)
    // CIDiscBlur ---> 環(huán)形卷積模糊(Available in iOS 9.0 and later)
    // CIMedianFilter ---> 中值模糊, 用于消除圖像噪點(diǎn), 無需設(shè)置radius(Available in iOS 9.0 and later)
    // CIMotionBlur ---> 運(yùn)動(dòng)模糊, 用于模擬相機(jī)移動(dòng)拍攝時(shí)的掃尾效果(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;
    }
    }

</pre>

  1. 調(diào)整圖片飽和度、亮度、對(duì)比度
    <pre>/**
  • 調(diào)整圖片飽和度, 亮度, 對(duì)比度
  • @param image 目標(biāo)圖片
  • @param saturation 飽和度
  • @param brightness 亮度: -1.0 ~ 1.0
  • @param contrast 對(duì)比度

*/

  • (UIImage *)colorControlsWithOriginalImage:(UIImage *)image
    saturation:(CGFloat)saturation
    brightness:(CGFloat)brightness
    contrast:(CGFloat)contrast{
    CIContext *context = [CIContext contextWithOptions:nil];
    CIImage *inputImage = [[CIImage alloc] initWithImage:image];
    CIFilter *filter = [CIFilter filterWithName:@"CIColorControls"];
    [filter setValue:inputImage forKey:kCIInputImageKey];

    [filter setValue:@(saturation) forKey:@"inputSaturation"];
    [filter setValue:@(brightness) forKey:@"inputBrightness"];
    [filter setValue:@(contrast) forKey:@"inputContrast"];

    CIImage *result = [filter valueForKey:kCIOutputImageKey];
    CGImageRef cgImage = [context createCGImage:result fromRect:[result extent]];
    UIImage *resultImage = [UIImage imageWithCGImage:cgImage];
    CGImageRelease(cgImage);
    return resultImage;
    }

</pre>

  1. 創(chuàng)建一張實(shí)時(shí)模糊效果 View (毛玻璃效果)
    <pre>//Avilable in iOS 8.0 and later
  • (UIVisualEffectView *)effectViewWithFrame:(CGRect)frame{
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    effectView.frame = frame;
    return effectView;
    }

</pre>

  1. 全屏截圖
    <pre>//全屏截圖
  • (UIImage *)shotScreen{
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UIGraphicsBeginImageContext(window.bounds.size);
    [window.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    }

</pre>

  1. 截取一張 view 生成圖片
    <pre>//截取view生成一張圖片
  • (UIImage *)shotWithView:(UIView *)view{
    UIGraphicsBeginImageContext(view.bounds.size);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
    }

</pre>

  1. 截取view中某個(gè)區(qū)域生成一張圖片
    <pre>//截取view中某個(gè)區(qū)域生成一張圖片
  • (UIImage *)shotWithView:(UIView *)view scope:(CGRect)scope{
    CGImageRef imageRef = CGImageCreateWithImageInRect([self shotWithView:view].CGImage, scope);
    UIGraphicsBeginImageContext(scope.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGRect rect = CGRectMake(0, 0, scope.size.width, scope.size.height);
    CGContextTranslateCTM(context, 0, rect.size.height);//下移
    CGContextScaleCTM(context, 1.0f, -1.0f);//上翻
    CGContextDrawImage(context, rect, imageRef);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGImageRelease(imageRef);
    CGContextRelease(context);
    return image;
    }

</pre>

  1. 壓縮圖片到指定尺寸大小
    <pre>//壓縮圖片到指定尺寸大小
  • (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage *resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIGraphicsEndImageContext();
    return resultImage;
    }

</pre>

  1. 壓縮圖片到指定文件大小
    <pre>//壓縮圖片到指定文件大小
  • (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{
    NSData *data = UIImageJPEGRepresentation(image, 1.0);
    CGFloat dataKBytes = data.length/1000.0;
    CGFloat maxQuality = 0.9f;
    CGFloat lastData = dataKBytes;
    while (dataKBytes > size && maxQuality > 0.01f) {
    maxQuality = maxQuality - 0.01f;
    data = UIImageJPEGRepresentation(image, maxQuality);
    dataKBytes = data.length/1000.0;
    if (lastData == dataKBytes) {
    break;
    }else{
    lastData = dataKBytes;
    }
    }
    return data;
    }

</pre>

  1. 獲取設(shè)備 IP 地址

需要先引入下頭文件:

Objective-C

1
2

import <ifaddrs.h>

import <arpa/inet.h>


<pre>//獲取設(shè)備 IP 地址

  • (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;
    }

</pre>


  1. 判斷字符串中是否含有空格
    <pre>+ (BOOL)isHaveSpaceInString:(NSString *)string{
    NSRange _range = [string rangeOfString:@" "];
    if (_range.location != NSNotFound) {
    return YES;
    }else {
    return NO;
    }
    }

</pre>

  1. 判斷字符串中是否含有某個(gè)字符串
    <pre>+ (BOOL)isHaveString:(NSString *)string1 InString:(NSString *)string2{
    NSRange _range = [string2 rangeOfString:string1];
    if (_range.location != NSNotFound) {
    return YES;
    }else {
    return NO;
    }
    }

</pre>

  1. 判斷字符串中是否含有中文
    <pre>+ (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;
    }

</pre>

  1. 判斷字符串是否全部為數(shù)字
    <pre>+ (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;
    }

</pre>

  1. 繪制虛線
    <pre>/*
    ** lineFrame: 虛線的 frame
    ** length: 虛線中短線的寬度
    ** spacing: 虛線中短線之間的間距
    ** color: 虛線中短線的顏色
    */
  • (UIView *)createDashedLineWithFrame:(CGRect)lineFrame
    lineLength:(int)length
    lineSpacing:(int)spacing
    lineColor:(UIColor *)color{
    UIView *dashedLine = [[UIView alloc] initWithFrame:lineFrame];
    dashedLine.backgroundColor = [UIColor clearColor];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:dashedLine.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(dashedLine.frame) / 2, CGRectGetHeight(dashedLine.frame))];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    [shapeLayer setStrokeColor:color.CGColor];
    [shapeLayer setLineWidth:CGRectGetHeight(dashedLine.frame)];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:length], [NSNumber numberWithInt:spacing], nil]];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    CGPathAddLineToPoint(path, NULL, CGRectGetWidth(dashedLine.frame), 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    [dashedLine.layer addSublayer:shapeLayer];
    return dashedLine;
    }

</pre>
1,打印View所有子視圖
<pre>po [[self view]recursiveDescription]</pre>

2,layoutSubviews調(diào)用的調(diào)用時(shí)機(jī)

<pre>* 當(dāng)視圖第一次顯示的時(shí)候會(huì)被調(diào)用

  • 當(dāng)這個(gè)視圖顯示到屏幕上了,點(diǎn)擊按鈕
  • 添加子視圖也會(huì)調(diào)用這個(gè)方法
  • 當(dāng)本視圖的大小發(fā)生改變的時(shí)候是會(huì)調(diào)用的
  • 當(dāng)子視圖的frame發(fā)生改變的時(shí)候是會(huì)調(diào)用的
  • 當(dāng)刪除子視圖的時(shí)候是會(huì)調(diào)用的</pre>

3,NSString過濾特殊字符
<pre>// 定義一個(gè)特殊字符的集合
NSCharacterSet set = [NSCharacterSet characterSetWithCharactersInString:
@"@/:;()¥「」"、[]{}#%-
+=|~<>$€?'@#$%&*()+'""];
// 過濾字符串的特殊字符
NSString *newString = [trimString stringByTrimmingCharactersInSet:set];</pre>

4,TransForm屬性
<pre>//平移按鈕
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformTranslate(transForm, 10, 0);

//旋轉(zhuǎn)按鈕
CGAffineTransform transForm = self.buttonView.transform;
self.buttonView.transform = CGAffineTransformRotate(transForm, M_PI_4);

//縮放按鈕
self.buttonView.transform = CGAffineTransformScale(transForm, 1.2, 1.2);

//初始化復(fù)位
self.buttonView.transform = CGAffineTransformIdentity;</pre>

5,去掉分割線多余15像素
<pre>首先在viewDidLoad方法加入以下代碼:
if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
[self.tableView setSeparatorInset:UIEdgeInsetsZero];
}
if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
[self.tableView setLayoutMargins:UIEdgeInsetsZero];
}
然后在重寫willDisplayCell方法

  • (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell
    forRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
    [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
    [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    }</pre>
    6,計(jì)算方法耗時(shí)時(shí)間間隔
    <pre>// 獲取時(shí)間間隔

define TICK CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

define TOCK NSLog(@"Time: %f", CFAbsoluteTimeGetCurrent() - start)</pre>

7,Color顏色宏定義
<pre>// 隨機(jī)顏色

define RANDOM_COLOR [UIColor colorWithRed:arc4random_uniform(256) / 255.0 green:arc4random_uniform(256) / 255.0 blue:arc4random_uniform(256) / 255.0 alpha:1]

// 顏色(RGB)

define RGBCOLOR(r, g, b) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:1]

// 利用這種方法設(shè)置顏色和透明值,可不影響子視圖背景色

define RGBACOLOR(r, g, b, a) [UIColor colorWithRed:(r)/255.0f green:(g)/255.0f blue:(b)/255.0f alpha:(a)]

</pre>

8,Alert提示宏定義
<pre>- (void)exitApplication {
AppDelegate *app = [UIApplication sharedApplication].delegate;
UIWindow *window = app.window;

[UIView animateWithDuration:1.0f animations:^{
    window.alpha = 0;
} completion:^(BOOL finished) {
    exit(0);
}];

}</pre>

9,NSArray 快速求總和 最大值 最小值 和 平均值
<pre>NSArray *array = [NSArray arrayWithObjects:@"2.0", @"2.3", @"3.0", @"4.0", @"10", nil];
CGFloat sum = [[array valueForKeyPath:@"@sum.floatValue"] floatValue];
CGFloat avg = [[array valueForKeyPath:@"@avg.floatValue"] floatValue];
CGFloat max =[[array valueForKeyPath:@"@max.floatValue"] floatValue];
CGFloat min =[[array valueForKeyPath:@"@min.floatValue"] floatValue];
NSLog(@"%fn%fn%fn%f",sum,avg,max,min);
</pre>

10修改Label中不同文字顏色
<pre>- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self editStringColor:self.label.text editStr:@"好" color:[UIColor blueColor]];
}

  • (void)editStringColor:(NSString *)string editStr:(NSString *)editStr color:(UIColor *)color {
    // string為整體字符串, editStr為需要修改的字符串
    NSRange range = [string rangeOfString:editStr];

    NSMutableAttributedString *attribute = [[NSMutableAttributedString alloc] initWithString:string];

    // 設(shè)置屬性修改字體顏色UIColor與大小UIFont
    [attribute addAttributes:@{NSForegroundColorAttributeName:color} range:range];

    self.label.attributedText = attribute;
    }</pre>

10,播放聲音
<pre>#import
// 1.獲取音效資源的路徑
NSString *path = [[NSBundle mainBundle]pathForResource:@"pour_milk" ofType:@"wav"];
// 2.將路勁轉(zhuǎn)化為url
NSURL *tempUrl = [NSURL fileURLWithPath:path];
// 3.用轉(zhuǎn)化成的url創(chuàng)建一個(gè)播放器
NSError *error = nil;
AVAudioPlayer *play = [[AVAudioPlayer alloc]initWithContentsOfURL:tempUrl error:&error];
self.player = play;
// 4.播放
[play play];</pre>

11檢測(cè)是否IPad Pro和其它設(shè)備型號(hào)
<pre>- (BOOL)isIpadPro
{
UIScreen *Screen = [UIScreen mainScreen];
CGFloat width = Screen.nativeBounds.size.width/Screen.nativeScale;
CGFloat height = Screen.nativeBounds.size.height/Screen.nativeScale;
BOOL isIpad =[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad;
BOOL hasIPadProWidth = fabs(width - 1024.f) = 8.0)</pre>

12修改Tabbar Item的屬性
// 修改標(biāo)題位置
self.tabBarItem.titlePositionAdjustment = UIOffsetMake(0, -10);
// 修改圖片位置
self.tabBarItem.imageInsets = UIEdgeInsetsMake(-3, 0, 3, 0);

// 批量修改屬性
for (UIBarItem *item in self.tabBarController.tabBar.items) {
    [item setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
             [UIFont fontWithName:@"Helvetica" size:19.0], NSFontAttributeName, nil]
                        forState:UIControlStateNormal];
}

// 設(shè)置選中和未選中字體顏色
[[UITabBar appearance] setShadowImage:[[UIImage alloc] init]];

//未選中字體顏色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor greenColor]} forState:UIControlStateNormal];

//選中字體顏色
[[UITabBarItem appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor cyanColor]} forState:UIControlStateSelected];

12,NULL – nil – Nil – NSNULL的區(qū)別
<pre>* nil是OC的,空對(duì)象,地址指向空(0)的對(duì)象。對(duì)象的字面零值

  • Nil是Objective-C類的字面零值

  • NULL是C的,空地址,地址的數(shù)值是0,是個(gè)長整數(shù)

  • NSNull用于解決向NSArray和NSDictionary等集合中添加空值的問題</pre>
    11,去掉BackBarButtonItem的文字
    <pre>[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60)
    forBarMetrics:UIBarMetricsDefault]</pre>

12,控件不能交互的一些原因
<pre>1,控件的userInteractionEnabled = NO
2,透明度小于等于0.01,aplpha
3,控件被隱藏的時(shí)候,hidden = YES
4,子視圖的位置超出了父視圖的有效范圍,子視圖無法交互,設(shè)置了。
5,需要交互的視圖,被其他視圖蓋住(其他視圖開啟了用戶交互)。</pre>

12,修改UITextField中Placeholder的文字顏色
<pre>[text setValue:[UIColor redColor] forKeyPath:@"_placeholderLabel.textColor"];
}</pre>

13,視圖的生命周期
<pre>1、 alloc 創(chuàng)建對(duì)象,分配空間
2、 init (initWithNibName) 初始化對(duì)象,初始化數(shù)據(jù)
3、 loadView 從nib載入視圖 ,除非你沒有使用xib文件創(chuàng)建視圖
4、 viewDidLoad 載入完成,可以進(jìn)行自定義數(shù)據(jù)以及動(dòng)態(tài)創(chuàng)建其他控件
5、 viewWillAppear視圖將出現(xiàn)在屏幕之前,馬上這個(gè)視圖就會(huì)被展現(xiàn)在屏幕上了
6、 viewDidAppear 視圖已在屏幕上渲染完成

1、viewWillDisappear 視圖將被從屏幕上移除之前執(zhí)行
2、viewDidDisappear 視圖已經(jīng)被從屏幕上移除,用戶看不到這個(gè)視圖了
3、dealloc 視圖被銷毀,此處需要對(duì)你在init和viewDidLoad中創(chuàng)建的對(duì)象進(jìn)行釋放.

viewVillUnload- 當(dāng)內(nèi)存過低,即將釋放時(shí)調(diào)用;
viewDidUnload-當(dāng)內(nèi)存過低,釋放一些不需要的視圖時(shí)調(diào)用。</pre>

14,應(yīng)用程序的生命周期
<pre>1,啟動(dòng)但還沒進(jìn)入狀態(tài)保存 :

  • (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions

2,基本完成程序準(zhǔn)備開始運(yùn)行:

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

3,當(dāng)應(yīng)用程序?qū)⒁敕腔顒?dòng)狀態(tài)執(zhí)行,應(yīng)用程序不接收消息或事件,比如來電話了:

  • (void)applicationWillResignActive:(UIApplication *)application

4,當(dāng)應(yīng)用程序入活動(dòng)狀態(tài)執(zhí)行,這個(gè)剛好跟上面那個(gè)方法相反:

  • (void)applicationDidBecomeActive:(UIApplication *)application

5,當(dāng)程序被推送到后臺(tái)的時(shí)候調(diào)用。所以要設(shè)置后臺(tái)繼續(xù)運(yùn)行,則在這個(gè)函數(shù)里面設(shè)置即可:

  • (void)applicationDidEnterBackground:(UIApplication *)application

6,當(dāng)程序從后臺(tái)將要重新回到前臺(tái)時(shí)候調(diào)用,這個(gè)剛好跟上面的那個(gè)方法相反:

  • (void)applicationWillEnterForeground:(UIApplication *)application

7,當(dāng)程序?qū)⒁顺鍪潜徽{(diào)用,通常是用來保存數(shù)據(jù)和一些退出前的清理工作:

  • (void)applicationWillTerminate:(UIApplication *)application
    </pre>
    15,判斷view是不是指定視圖的子視圖
    <pre> BOOL isView = [textView isDescendantOfView:self.view];
    </pre>

16,判斷對(duì)象是否遵循了某協(xié)議
<pre>if ([self.selectedController conformsToProtocol:@protocol(RefreshPtotocol)]) {
[self.selectedController performSelector:@selector(onTriggerRefresh)];
}</pre>

17,頁面強(qiáng)制橫屏
<pre>#pragma mark - 強(qiáng)制橫屏代碼

  • (BOOL)shouldAutorotate{
    //是否支持轉(zhuǎn)屏
    return NO;
    }
  • (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    //支持哪些轉(zhuǎn)屏方向
    return UIInterfaceOrientationMaskLandscape;
    }
  • (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    return UIInterfaceOrientationLandscapeRight;
    }
  • (BOOL)prefersStatusBarHidden{
    return NO;
    }</pre>

18,系統(tǒng)鍵盤通知消息
<pre>1、UIKeyboardWillShowNotification-將要彈出鍵盤
2、UIKeyboardDidShowNotification-顯示鍵盤
3、UIKeyboardWillHideNotification-將要隱藏鍵盤
4、UIKeyboardDidHideNotification-鍵盤已經(jīng)隱藏
5、UIKeyboardWillChangeFrameNotification-鍵盤將要改變frame
6、UIKeyboardDidChangeFrameNotification-鍵盤已經(jīng)改變frame</pre>

19,關(guān)閉navigationController的滑動(dòng)返回手勢(shì)
<pre>self.navigationController.interactivePopGestureRecognizer.enabled = NO;</pre>
20,設(shè)置狀態(tài)欄背景為任意的顏色
<pre>- (void)setStatusColor
{
UIView *statusBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
statusBarView.backgroundColor = [UIColor orangeColor];
[self.view addSubview:statusBarView];
}</pre>

22,Label行間距
<pre>-(void)test{
NSMutableAttributedString *attributedString =
[[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle setLineSpacing:3];

//調(diào)整行間距       

[attributedString addAttribute:NSParagraphStyleAttributeName
value:paragraphStyle
range:NSMakeRange(0, [self.contentLabel.text length])];
self.contentLabel.attributedText = attributedString;
}
</pre>
23,UIImageView填充模式
<pre>@"UIViewContentModeScaleToFill", // 拉伸自適應(yīng)填滿整個(gè)視圖
@"UIViewContentModeScaleAspectFit", // 自適應(yīng)比例大小顯示
@"UIViewContentModeScaleAspectFill", // 原始大小顯示
@"UIViewContentModeRedraw", // 尺寸改變時(shí)重繪
@"UIViewContentModeCenter", // 中間
@"UIViewContentModeTop", // 頂部
@"UIViewContentModeBottom", // 底部
@"UIViewContentModeLeft", // 中間貼左
@"UIViewContentModeRight", // 中間貼右
@"UIViewContentModeTopLeft", // 貼左上
@"UIViewContentModeTopRight", // 貼右上
@"UIViewContentModeBottomLeft", // 貼左下
@"UIViewContentModeBottomRight", // 貼右下</pre>

24,宏定義檢測(cè)block是否可用
<pre>#define BLOCK_EXEC(block, ...) if (block) { block(VA_ARGS); };
// 宏定義之前的用法
if (completionBlock) {
completionBlock(arg1, arg2);
}
// 宏定義之后的用法
BLOCK_EXEC(completionBlock, arg1, arg2);</pre>

25,Debug欄打印時(shí)自動(dòng)把Unicode編碼轉(zhuǎn)化成漢字
<pre>// 有時(shí)候我們?cè)趚code中打印中文,會(huì)打印出Unicode編碼,還需要自己去一些在線網(wǎng)站轉(zhuǎn)換,有了插件就方便多了。
DXXcodeConsoleUnicodePlugin 插件</pre>

26,設(shè)置狀態(tài)欄文字樣式顏色
<pre>[[UIApplication sharedApplication] setStatusBarHidden:NO];
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];</pre>

26,自動(dòng)生成模型代碼的插件
<pre>
可自動(dòng)生成模型的代碼,省去寫模型代碼的時(shí)間
ESJsonFormat-for-Xcode</pre>

27,iOS中的一些手勢(shì)
<pre>輕擊手勢(shì)(TapGestureRecognizer)
輕掃手勢(shì)(SwipeGestureRecognizer)
長按手勢(shì)(LongPressGestureRecognizer)
拖動(dòng)手勢(shì)(PanGestureRecognizer)
捏合手勢(shì)(PinchGestureRecognizer)
旋轉(zhuǎn)手勢(shì)(RotationGestureRecognizer)</pre>

27,iOS 開發(fā)中一些相關(guān)的路徑
<pre>模擬器的位置:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs

文檔安裝位置:
/Applications/Xcode.app/Contents/Developer/Documentation/DocSets

插件保存路徑:
~/Library/ApplicationSupport/Developer/Shared/Xcode/Plug-ins

自定義代碼段的保存路徑:
~/Library/Developer/Xcode/UserData/CodeSnippets/
如果找不到CodeSnippets文件夾,可以自己新建一個(gè)CodeSnippets文件夾。

證書路徑
~/Library/MobileDevice/Provisioning Profiles
</pre>
28,獲取 iOS 路徑的方法
<pre>獲取家目錄路徑的函數(shù)
NSString *homeDir = NSHomeDirectory();

獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];

獲取Documents目錄路徑的方法
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDir = [paths objectAtIndex:0];

獲取tmp目錄路徑的方法:
NSString *tmpDir = NSTemporaryDirectory();</pre>

29,字符串相關(guān)操作
<pre>去除所有的空格
[str stringByReplacingOccurrencesOfString:@" " withString:@""]

去除首尾的空格
[str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

  • (NSString *)uppercaseString; 全部字符轉(zhuǎn)為大寫字母
  • (NSString *)lowercaseString 全部字符轉(zhuǎn)為小寫字母</pre>
    30, CocoaPods pod install/pod update更新慢的問題
    <pre>pod install --verbose --no-repo-update
    pod update --verbose --no-repo-update
    如果不加后面的參數(shù),默認(rèn)會(huì)升級(jí)CocoaPods的spec倉庫,加一個(gè)參數(shù)可以省略這一步,然后速度就會(huì)提升不少。</pre>

31,MRC和ARC混編設(shè)置方式
<pre>在XCode中targets的build phases選項(xiàng)下Compile Sources下選擇 不需要arc編譯的文件
雙擊輸入 -fno-objc-arc 即可

MRC工程中也可以使用ARC的類,方法如下:
在XCode中targets的build phases選項(xiàng)下Compile Sources下選擇要使用arc編譯的文件
雙擊輸入 -fobjc-arc 即可</pre>

32,把tableview里cell的小對(duì)勾的顏色改成別的顏色
<pre>_mTableView.tintColor = [UIColor redColor];</pre>
33,調(diào)整tableview的separaLine線的位置
<pre>tableView.separatorInset = UIEdgeInsetsMake(0, 100, 0, 0);
</pre>

34,設(shè)置滑動(dòng)的時(shí)候隱藏navigation bar

navigationController.hidesBarsOnSwipe = Yes

35,自動(dòng)處理鍵盤事件,實(shí)現(xiàn)輸入框防遮擋的插件
IQKeyboardManager
https://github.com/hackiftekhar/IQKeyboardManager

36,Quartz2D相關(guān)

<pre>圖形上下是一個(gè)CGContextRef類型的數(shù)據(jù)。
圖形上下文包含:
1,繪圖路徑(各種各樣圖形)
2,繪圖狀態(tài)(顏色,線寬,樣式,旋轉(zhuǎn),縮放,平移)
3,輸出目標(biāo)(繪制到什么地方去?UIView、圖片)

1,獲取當(dāng)前圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();
2,添加線條
CGContextMoveToPoint(ctx, 20, 20);
3,渲染
CGContextStrokePath(ctx);
CGContextFillPath(ctx);
4,關(guān)閉路徑
CGContextClosePath(ctx);
5,畫矩形
CGContextAddRect(ctx, CGRectMake(20, 20, 100, 120));
6,設(shè)置線條顏色
[[UIColor redColor] setStroke];
7, 設(shè)置線條寬度
CGContextSetLineWidth(ctx, 20);
8,設(shè)置頭尾樣式
CGContextSetLineCap(ctx, kCGLineCapSquare);
9,設(shè)置轉(zhuǎn)折點(diǎn)樣式
CGContextSetLineJoin(ctx, kCGLineJoinBevel);
10,畫圓
CGContextAddEllipseInRect(ctx, CGRectMake(30, 50, 100, 100));
11,指定圓心
CGContextAddArc(ctx, 100, 100, 50, 0, M_PI * 2, 1);
12,獲取圖片上下文
UIGraphicsGetImageFromCurrentImageContext();
13,保存圖形上下文
CGContextSaveGState(ctx)
14,恢復(fù)圖形上下文
CGContextRestoreGState(ctx)</pre>

37,屏幕截圖
<pre> // 1. 開啟一個(gè)與圖片相關(guān)的圖形上下文
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);

// 2. 獲取當(dāng)前圖形上下文
CGContextRef ctx = UIGraphicsGetCurrentContext();

// 3. 獲取需要截取的view的layer
[self.view.layer renderInContext:ctx];

// 4. 從當(dāng)前上下文中獲取圖片
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

// 5. 關(guān)閉圖形上下文
UIGraphicsEndImageContext();

// 6. 把圖片保存到相冊(cè)
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);</pre>

37,左右抖動(dòng)動(dòng)畫
<pre>//1, 創(chuàng)建核心動(dòng)畫
CAKeyframeAnimation *keyAnima = [CAKeyframeAnimation animation];

//2, 告訴系統(tǒng)執(zhí)行什么動(dòng)畫。
keyAnima.keyPath = @"transform.rotation";
keyAnima.values = @[@(-M_PI_4 /90.0 * 5),@(M_PI_4 /90.0 * 5),@(-M_PI_4 /90.0 * 5)];

// 3, 執(zhí)行完之后不刪除動(dòng)畫
keyAnima.removedOnCompletion = NO;

// 4, 執(zhí)行完之后保存最新的狀態(tài)
keyAnima.fillMode = kCAFillModeForwards;

// 5, 動(dòng)畫執(zhí)行時(shí)間
keyAnima.duration = 0.2;

// 6, 設(shè)置重復(fù)次數(shù)。
keyAnima.repeatCount = MAXFLOAT;

// 7, 添加核心動(dòng)畫
[self.iconView.layer addAnimation:keyAnima forKey:nil];</pre>
38,CALayer 的知識(shí)
<pre>CALayer 負(fù)責(zé)視圖中顯示內(nèi)容和動(dòng)畫
UIView 負(fù)責(zé)監(jiān)聽和響應(yīng)事件

創(chuàng)建UIView對(duì)象時(shí),UIView內(nèi)部會(huì)自動(dòng)創(chuàng)建一個(gè)圖層(既CALayer)
UIView本身不具備顯示的功能,是它內(nèi)部的層才有顯示功能.

CALayer屬性:
position 中點(diǎn)(由anchorPoint決定)
anchorPoint 錨點(diǎn)
borderColor 邊框顏色
borderWidth 邊框?qū)挾?br> cornerRadius 圓角半徑
shadowColor 陰影顏色
contents 內(nèi)容
opacity 透明度
shadowOpacity 偏移
shadowRadius 陰影半徑
shadowColor 陰影顏色
masksToBounds 裁剪</pre>

39,性能相關(guān)
<pre>1. 視圖復(fù)用,比如UITableViewCell,UICollectionViewCell.

  1. 數(shù)據(jù)緩存,比如用SDWebImage實(shí)現(xiàn)圖片緩存。
  2. 任何情況下都不能堵塞主線程,把耗時(shí)操作盡量放到子線程。
  3. 如果有多個(gè)下載同時(shí)并發(fā),可以控制并發(fā)數(shù)。
  4. 在合適的地方盡量使用懶加載。
  5. 重用重大開銷對(duì)象,比如:NSDateFormatter、NSCalendar。
  6. 選擇合適的數(shù)據(jù)存儲(chǔ)。
  7. 避免循環(huán)引用。避免delegate用retain、strong修飾,block可能導(dǎo)致循環(huán)引用,NSTimer也可能導(dǎo)致內(nèi)存泄露等。
  8. 當(dāng)涉及到定位的時(shí)候,不用的時(shí)候最好把定位服務(wù)關(guān)閉。因?yàn)槎ㄎ缓碾姟⒘髁俊?/li>
  9. 加鎖對(duì)性能有重大開銷。
  10. 界面最好不要添加過多的subViews.
  11. TableView 如果不同行高,那么返回行高,最好做緩存。
  12. Viewdidload 里盡量不要做耗時(shí)操作。</pre>

40,驗(yàn)證身份證號(hào)碼
<pre>//驗(yàn)證身份證號(hào)碼

  • (BOOL)checkIdentityCardNo:(NSString)cardNo
    {
    if (cardNo.length != 18) {
    return NO;
    }
    NSArray
    codeArray = [NSArray arrayWithObjects:@"7",@"9",@"10",@"5",@"8",@"4",@"2",@"1",@"6",@"3",@"7",@"9",@"10",@"5",@"8",@"4",@"2", nil];
    NSDictionary* checkCodeDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:@"1",@"0",@"X",@"9",@"8",@"7",@"6",@"5",@"4",@"3",@"2", nil] forKeys:[NSArray arrayWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10", nil]];

    NSScanner* scan = [NSScanner scannerWithString:[cardNo substringToIndex:17]];

    int val;
    BOOL isNum = [scan scanInt:&val] && [scan isAtEnd];
    if (!isNum) {
    return NO;
    }
    int sumValue = 0;

    for (int i =0; i
    </pre>
    41,響應(yīng)者鏈條順序
    <pre>1> 當(dāng)應(yīng)用程序啟動(dòng)以后創(chuàng)建 UIApplication 對(duì)象

2> 然后啟動(dòng)“消息循環(huán)”監(jiān)聽所有的事件

3> 當(dāng)用戶觸摸屏幕的時(shí)候, "消息循環(huán)"監(jiān)聽到這個(gè)觸摸事件

4> "消息循環(huán)" 首先把監(jiān)聽到的觸摸事件傳遞了 UIApplication 對(duì)象

5> UIApplication 對(duì)象再傳遞給 UIWindow 對(duì)象

6> UIWindow 對(duì)象再傳遞給 UIWindow 的根控制器(rootViewController)

7> 控制器再傳遞給控制器所管理的 view

8> 控制器所管理的 View 在其內(nèi)部搜索看本次觸摸的點(diǎn)在哪個(gè)控件的范圍內(nèi)(調(diào)用Hit test檢測(cè)是否在這個(gè)范圍內(nèi))

9> 找到某個(gè)控件以后(調(diào)用這個(gè)控件的 touchesXxx 方法), 再一次向上返回, 最終返回給"消息循環(huán)"

10> "消息循環(huán)"知道哪個(gè)按鈕被點(diǎn)擊后, 在搜索這個(gè)按鈕是否注冊(cè)了對(duì)應(yīng)的事件, 如果注冊(cè)了, 那么就調(diào)用這個(gè)"事件處理"程序。(一般就是執(zhí)行控制器中的"事件處理"方法)</pre>

42,使用函數(shù)式指針執(zhí)行方法和忽略performSelector方法的時(shí)候警告
<pre>不帶參數(shù)的:
SEL selector = NSSelectorFromString(@"someMethod");
IMP imp = [_controller methodForSelector:selector];
void (*func)(id, SEL) = (void *)imp;
func(_controller, selector);

帶參數(shù)的:
SEL selector = NSSelectorFromString(@"processRegion:ofView:");
IMP imp = [_controller methodForSelector:selector];
CGRect (*func)(id, SEL, CGRect, UIView *) = (void *)imp;
CGRect result = func(_controller, selector, someRect, someView);

忽略警告:

pragma clang diagnostic push

pragma clang diagnostic ignored "-Warc-performSelector-leaks"

[someController performSelector: NSSelectorFromString(@"someMethod")]

pragma clang diagnostic pop

如果需要忽視的警告有多處,可以定義一個(gè)宏:

define SuppressPerformSelectorLeakWarning(Stuff)

do {
_Pragma("clang diagnostic push")
_Pragma("clang diagnostic ignored "-Warc-performSelector-leaks"")
Stuff;
_Pragma("clang diagnostic pop")
} while (0)
使用方法:
SuppressPerformSelectorLeakWarning(
[_target performSelector:_action withObject:self]
);
</pre>

43,UIApplication的簡單使用
<pre>--------設(shè)置角標(biāo)數(shù)字--------
//獲取UIApplication對(duì)象
UIApplication *ap = [UIApplication sharedApplication];
//在設(shè)置之前, 要注冊(cè)一個(gè)通知,從ios8之后,都要先注冊(cè)一個(gè)通知對(duì)象.才能夠接收到提醒.
UIUserNotificationSettings *notice =
[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
//注冊(cè)通知對(duì)象
[ap registerUserNotificationSettings:notice];
//設(shè)置提醒數(shù)字
ap.applicationIconBadgeNumber = 20;

--------設(shè)置聯(lián)網(wǎng)狀態(tài)--------
UIApplication *ap = [UIApplication sharedApplication];
ap.networkActivityIndicatorVisible = YES;</pre>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,818評(píng)論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,185評(píng)論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,656評(píng)論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,647評(píng)論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,446評(píng)論 6 405
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,951評(píng)論 1 321
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,041評(píng)論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,189評(píng)論 0 287
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,718評(píng)論 1 333
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,602評(píng)論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,800評(píng)論 1 369
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,316評(píng)論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,045評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,419評(píng)論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,671評(píng)論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,420評(píng)論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,755評(píng)論 2 371

推薦閱讀更多精彩內(nèi)容