博客> iOS-小常识知识点 (持续更新)
iOS-小常识知识点 (持续更新)
2017-05-22 00:58 评论:0 阅读:476 OS_JJ
ios 报错累计整理

第一.app如何添加AirDrop文件分享功能

    苹果在iOS 7 SDK中集成了UIActivityViewController类,可以让你很简单地就能把AirDrop功能整合进app中!
    MobileVLCKit 第三方 多格式支持 视频播放!

第二.内存泄露分析及解决

    静态分析内存泄露 使用Xcode自带的Analyze功能(Product-> Analyze)(Shift + Command + B),对代码进行静态分析,对于内存泄露(Potential Memory Leak), 未使用局部变量(dead store),逻辑错误(Logic Flaws)以及API使用问题(API-usage)等明确的展示出来。 静态分析的内存泄露情况比较简单,开发者都能很快的解决。这里不做赘述。

    动态分析内存泄露 使用Xcode自带的Profile功能(Product-> Profile)(Command + i)弹出工具框,选择Leaks打开,选择运行设备点左上角的Record录制按钮,项目就会在已选好的设备上运行,并开始录制内存检测情况。选Leaks查看泄露情况,在Leaks的详细菜单Details选项里选调用树Call Tree,可查看所有内存泄露发生在哪些地方。再在右侧的齿轮设置-Call Tree-勾选Hide System Libraries,则可直接看内存泄露发生的函数名、方法名。点击函数名、方法名,可直接跳到函数方法的细节,可以看到哪一句代码出现了内存泄露,以及泄露了多少内存。
接下来就要回到Xcode,找到出现内存泄露的函数方法,仔细分析如何出现的内存泄露; 一般使用ARC,按照上面一提到的内存理解和编码习惯是不会出现内存泄露的。但我们在开发过程中,经常要使用第三方的一些类库,特别是涉及到加密的类库,用c或c++来编码的加密解密方法,会出现内存泄露。此时,我们要明白这些内存分配,需要手动释放。要一步一步看,哪里分配了内存,在使用完之后一定要记得释放free它。

调试内存泄露是一件让人头疼的事,如果你不想头疼,请保持良好的编码习惯。并在开发到一个阶段时,就要及时对应用进行内存泄露分析。发现问题,及时修复。

第三.block循环利用导致内存泄漏

    A *a = [[A alloc] init];
     a.finishBlock = ^(NSDictionary paraments){ [a doSomething]; }; 
    对于这种在block块里引用对象a的情况,要在创建对象a时加修饰符block来防止循环引用。
     block A *a = [[A alloc] init]; 
     a.finishBlock = ^(NSDictionary paraments){ [a doSomething]; }; 
    或 A __block a = [[A alloc] init]; a.finishBlock = ^(NSDictionary paraments){ [a doSomething]; };
     或者,需要在block中调用用self的方法、属性、变量时,可以这样写__weak typeof(self) weakSelf = self;在block中使用weakSelf。
    __weak typeof(self) weakSelf = self; [b doSomethingWithFinishBlock:^{ weakSelf.text = @"内存检测"; [weakSelf doSomething]; }]; 

第四.label 的空格属性和局部字段颜色和大小以及字间距

    _//空格属性_
    设置 label 的 autoresizingMask 为 NO ,可以使用空格间隔字符串!

    _//获取要调整颜色的文字位置,调整颜色  ,改变字体大小和字间距_
    [thirdLab setAttributedText:[self changeLabelWithText:@"点击按钮去注册"]];

    -(NSMutableAttributedString*)changeLabelWithText:(NSString*)needText  
    {            
        NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:needText];

        [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20] range:NSMakeRange(0,1)];
        [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithRed:51/255.0 green:3/255.0 blue:4/255.0 alpha:1] range:NSMakeRange(0,1)];
      [attrString addAttribute:NSKernAttributeName value:@1.0f range:NSMakeRange(0, needText.length)];

        [attrString addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(1,needText.length-1)];
        [attrString addAttribute:NSForegroundColorAttributeName value:[UIColor blackColor] range:NSMakeRange(1,needText.length-1)];

        return attrString;            
    }

第五.过滤字符串

    // 定义一个特殊字符的集合
    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:
    @"@/:;()¥「」"、[]{}#%-*+=_\\|~<>$€^•'@#$%^&*()_+'\""];
    // 过滤字符串的特殊字符
    NSString *newString = [trimString stringByTrimmingCharactersInSet:set];    

第六.iOS应用直接退出

    - (void)exitApplication {
        AppDelegate *app = [UIApplication sharedApplication].delegate;
        UIWindow *window = app.window;

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

第七.label 行间距

    -(void)test{
        NSMutableAttributedString *attributedString =    
       [[NSMutableAttributedString alloc] initWithString:self.contentLabel.text];
        NSMutableParagraphStyle *paragraphStyle =  [[NSMutableParagraphStyle alloc] init];  
       [paragraphStyle setLineSpacing:3];

        //调整行间距       
       [attributedString addAttribute:NSParagraphStyleAttributeName 
                             value:paragraphStyle 
                             range:NSMakeRange(0, [self.contentLabel.text length])];
         self.contentLabel.attributedText = attributedString;
    }

第八.设置滑动的时候隐藏 navigationbar

    第1种:
        navigationController.hidesBarsOnSwipe = Yes

    第2种:
        //1.当我们的手离开屏幕时候隐藏
    - (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
    { 
        if(velocity.y > 0) 
        {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
        } else {
        [self.navigationController setNavigationBarHidden:NO animated:YES]; 
        }
    }
    velocity.y这个量,在上滑和下滑时,变化极小(小数),但是因为方向不同,有正负之分,这就很好处理  了。

第九.屏幕截图

     // 1. 开启一个与图片相关的图形上下文
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size,NO,0.0);

    // 2. 获取当前图形上下文
    CGContextRef ctx = UIGraphicsGetCurrentContext();

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

    // 4. 从当前上下文中获取图片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();

    // 5. 关闭图形上下文
    UIGraphicsEndImageContext();

    // 6. 把图片保存到相册
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);

第十.导航栏相关

//隐藏导航栏上的返回字体 //Swift UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -60), forBarMetrics: .Default) //OC [[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(0, -60) forBarMetrics:UIBarMetricsDefault];

//自定义导航栏的左右按钮 UIButton searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 90, 0, 30, 44)]; UIBarButtonItem seaBtn = [[UIBarButtonItem alloc] initWithCustomView:searchBtn]; self.navigationItem.rightBarButtonItem = seaBtn;

第十一.去掉 tabbar 和 navgationbar 的黑线

      //去掉tabBar顶部线条
    CGRect rect = CGRectMake(0, 0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    [self.tabBar setBackgroundImage:img];
    [self.tabBar setShadowImage:img];
    //[self.navigationController.navigationBar setBackgroundImage:img];
    //self.navigationController.navigationBar.shadowImage = ima;

    self.tabBar.backgroundColor = SLIVERYCOLOR;

第十二.判断字符串中是否含有中文

    -(BOOL)isChinese:(NSString *)str{
        NSString *match=@"(^[\u4e00-\u9fa5]+$)";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF matches %@", match];
        return [predicate evaluateWithObject:str];
    }

第十三.解决父视图和子视图的手势冲突

    /** 解决手势冲突 */
    - (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
        if ([touch.view isDescendantOfView:cicView]) {
            return NO;
        }
        return YES;
    }

第十四.NSDate与NSString的相互转化

    -(NSString *)dateToString:(NSDate *)date {
      // 初始化时间格式控制器
      NSDateFormatter *matter = [[NSDateFormatter alloc] init];
      // 设置设计格式
      [matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
      // 进行转换
      NSString *dateStr = [matter stringFromDate:date];
      return dateStr;
    }
    -(NSDate *)stringToDate:(NSString *)dateStr {

      // 初始化时间格式控制器
      NSDateFormatter *matter = [[NSDateFormatter alloc] init];
      // 设置设计格式
      [matter setDateFormat:@"yyyy-MM-dd hh:mm:ss zzz"];
      // 进行转换
      NSDate *date = [matter dateFromString:dateStr];
      return date;
    }

第十五.Xcode 8 注释设置

    打开终端,命令运行: sudo /usr/libexec/xpccachectl
    然后必须重启电脑后生效

十六.删除storyboard的方法

    一般情况下,我们有时候不想用storyboard,但是直接删除的话,Xcode就会报错。那我今天就来讲一下,正确删除storyboard的方法。

    第一,直接将工程中的storyboard直接删除掉,这样你觉得就OK了?你错了,还是要有第二步的。

    第二,找到plist文件,将plist文件中的Main storyboard file base name删除掉,如图所示

十七.ASCII 和 NSString 的相互转换

    // NSString to ASCII
    NSString *string = @"A";
    int asciiCode = [string characterAtIndex:0]; //65

    //ASCII to NSString
    int asciiCode = 65;
    NSString *string =[NSString stringWithFormat:@"%c",asciiCode]; //A

十八.获取当前连接的wifi名称

        NSString *wifiName = @"Not Found";

        CFArrayRef myArray = CNCopySupportedInterfaces();

        if (myArray != nil) {

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

            if (myDict != nil) {

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

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

            }

        }

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

十九.苹果自带的下拉刷新方法

        //设置下拉刷新 UIRefreshControl *refresh = [[UIRefreshControl alloc] init];

        NSDictionary dict = @{NSForegroundColorAttributeName:[UIColor redColor]}; 
        NSAttributedString string = [[NSAttributedString alloc] initWithString:@"帮你署最新。。" attributes:dict]; 
        refresh.attributedTitle = string;

        [self.tableView addSubview:refresh];

二十.显示和隐藏系统文件

        显示Mac隐藏文件的命令:

        defaults write com.apple.finder AppleShowAllFiles -bool true

        隐藏Mac隐藏文件的命令:

        defaults write com.apple.finder AppleShowAllFiles -bool false

二十一.跨控制器跳转返回

    for (UIViewController *controller in self.navigationController.viewControllers) { 
        if ([controller isKindOfClass:[@“你要返回的控制器类名” class]]) {
             [self.navigationController popToViewController:controller animated:YES];
         }
     }

二十二. layer.cornerRadius 圆角流畅性的优化

    loginBtn.layer.cornerRadius = 10;
    loginBtn.layer.shouldRasterize = YES;
    loginBtn.layer.rasterizationScale = [UIScreen mainScreen].scale;

二十三.导航栏和下方视图间隔距离消失

     //不间隔
    self.automaticallyAdjustsScrollViewInsets=YES;

    //不重叠
    self.edgesForExtendedLayout = UIRectEdgeNone

二十四.毛玻璃效果(ios8.0以后的版本)

    UIVisualEffectView *visualEffectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    visualEffectView.frame = CGRectMake(0, 0, 320*[FlexibleFrame ratio], 180*[FlexibleFrame ratio]);
    visualEffectView.alpha = 1.0;

二十五.工作中常用的第三方

传送

二十六.PCH文件中的小玩意

    创建.pch文件时 , BuildSetting 中的 Prefix Header 中的路径开头可以写  $(SRCROOT)/工程地址, 这样写的好处可以使你的挪动代码不用手动更换路径!

二十七.如何点击谷歌地图获取所在位置经纬度?

链接

    调用谷歌地图 mapView:didTapAtCoordinate:  方法,即可获得!

二十八.AppIcon 和 launch image 尺寸相关

传送

二十九.iO中判断两个数组是否相同

    NSArray *array1 = [NSArray arrayWithObjects:@"a", @"b", @"c",  nil];
    NSArray *array2 = [NSArray arrayWithObjects:@"d", @"a", @"c",  nil];
    bool bol = false;

    //创建俩新的数组
    NSMutableArray *oldArr = [NSMutableArray arrayWithArray:array1];
    NSMutableArray *newArr = [NSMutableArray arrayWithArray:array2];

    //对数组1排序。
    [oldArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return obj1 > obj2;
    }];

    //对数组2排序。
    [newArr sortUsingComparator:^NSComparisonResult(id obj1, id obj2){
        return obj1 > obj2;
    }];

    if (newArr.count == oldArr.count) {

        bol = true;
        for (int16_t i = 0; i < oldArr.count; i++) {

            id c1 = [oldArr objectAtIndex:i];
            id newc = [newArr objectAtIndex:i];

            if (![newc isEqualToString:c1]) {
                bol = false;
                break;
            }
        }
    }

    if (bol) {
        NSLog(@" ------------- 两个数组的内容相同!");
    }
    else {
        NSLog(@"-=-------------两个数组的内容不相同!");
    }

三十.将阿拉伯数字转换成中文汉字(例:30 -- 三十)

    - (NSString *)translationArabicNum:(NSInteger)arabicNum
    {
        NSString *arabicNumStr = [NSString stringWithFormat:@"%ld",(long)arabicNum];
        NSArray *arabicNumeralsArray = @[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"0"];
        NSArray *chineseNumeralsArray = @[@"一",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"零"];
        NSArray *digits = @[@"个",@"十",@"百",@"千",@"万",@"十",@"百",@"千",@"亿",@"十",@"百",@"千",@"兆"];
        NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:chineseNumeralsArray forKeys:arabicNumeralsArray];

        if (arabicNum < 20> 9) {
            if (arabicNum == 10) {
                return @"十";
            }else{
                NSString *subStr1 = [arabicNumStr substringWithRange:NSMakeRange(1, 1)];
                NSString *a1 = [dictionary objectForKey:subStr1];
                NSString *chinese1 = [NSString stringWithFormat:@"十%@",a1];
                return chinese1;
            }
        }else{
            NSMutableArray *sums = [NSMutableArray array];
            for (int i = 0; i &lt; arabicNumStr.length; i ++)
            {
                NSString *substr = [arabicNumStr substringWithRange:NSMakeRange(i, 1)];
                NSString *a = [dictionary objectForKey:substr];
                NSString *b = digits[arabicNumStr.length -i-1];
                NSString *sum = [a stringByAppendingString:b];

                if ([a isEqualToString:chineseNumeralsArray[9]])
                {
                    if([b isEqualToString:digits[4]] || [b isEqualToString:digits[8]])
                    {
                        sum = b;
                        if ([[sums lastObject] isEqualToString:chineseNumeralsArray[9]])
                        {
                            [sums removeLastObject];
                        }
                    }else
                    {
                        sum = chineseNumeralsArray[9];
                    }

                    if ([[sums lastObject] isEqualToString:sum])
                    {
                        continue;
                    }
                }

                [sums addObject:sum];

            }
            NSString *sumStr = [sums  componentsJoinedByString:@""];
            NSString *chinese = [sumStr substringToIndex:sumStr.length-1];
            return chinese;
        }
    }

三十.屏幕渲染--颜色渐变

        CAGradientLayer *gradientLayer = [CAGradientLayer layer];
        gradientLayer.colors = @[(__bridge id)[UIColor whiteColor].CGColor,(__bridge id)[UIColor grayColor].CGColor,(__bridge id)[UIColor whiteColor].CGColor];
        gradientLayer.locations = @[@0.2,@0.65,@0.75];
        gradientLayer.startPoint = CGPointMake(0, 0);
        gradientLayer.endPoint = CGPointMake(1.0, 0);
        gradientLayer.frame = CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 2);
        [self.view.layer addSublayer:gradientLayer];

三十一.快速求和,最大值,最小值,平均值

    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];

三十二.对比时间差

 71F25BDF-1A6D-4132-9CB3-1A08D71198C7.png

    -(int)max:(NSDate *)datatime
    {
        //创建日期格式化对象
        NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
        NSDate *  senddate=[NSDate date];
        NSString *  locationString=[dateFormatter stringFromDate:senddate];
        NSDate *date=[dateFormatter dateFromString:locationString];
        //取两个日期对象的时间间隔:
        //这里的NSTimeInterval 并不是对象,是基本型,其实是double类型,是由c定义的:typedef double NSTimeInterval;
        NSTimeInterval time=[date timeIntervalSinceDate:datatime];
        int days=((int)time)/(3600*24);
        return days;
    }

三十三.请求定位权限以及定位属性

    _在地图页面放入下面代码:_
        //定位管理器
        _locationManager=[[CLLocationManager alloc]init];
        //如果没有授权则请求用户授权
        if ([CLLocationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined){
            [_locationManager requestWhenInUseAuthorization];
        }else if([CLLocationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
            //设置代理
            _locationManager.delegate=self;
            //设置定位精度
            _locationManager.desiredAccuracy=kCLLocationAccuracyBest;
            //定位频率,每隔多少米定位一次
            CLLocationDistance distance=10.0;//十米定位一次
            _locationManager.distanceFilter=distance;
            //启动跟踪定位
            [_locationManager startUpdatingLocation];
        }

三十四.将几张图片合成为一张

    - (UIImage *)composeWithHeader:(UIImage *)header content:(UIImage *)content footer:(UIImage *)footer{
        CGSize size = CGSizeMake(content.size.width, header.size.height +content.size.height +footer.size.height);
        UIGraphicsBeginImageContext(size);
        [header drawInRect:CGRectMake(0,
                                      0,
                                      header.size.width,
                                      header.size.height)];
        [content drawInRect:CGRectMake(0,
                                       header.size.height,
                                       content.size.width,
                                       content.size.height)];
        [footer drawInRect:CGRectMake(0,
                                      header.size.height+content.size.height,
                                      footer.size.width,
                                      footer.size.height)];

        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image;
}

三十五.按钮的选择状态及与BarButton的结合使用

      self.barRightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.barRightBtn.frame = CGRectMake(WIDTH-20, 30, 80, 30);
        [self.barRightBtn setTitle:@"停止扫描" forState:UIControlStateNormal];
        [self.barRightBtn setTitle:@"开始扫描" forState:UIControlStateSelected];

        [self.barRightBtn setTitleColor:BLUECOLOR forState:UIControlStateNormal];
        self.barRightBtn.titleLabel.font = [UIFont systemFontOfSize:18];
        [[self.barRightBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
            self.barRightBtn.selected = !self.barRightBtn.selected;

            if (self.barRightBtn.selected) {
                [self endScanIbeacon];
            }else{
                [self startScanIbecan];
            }
        }];

        UIBarButtonItem *barBtn = [[UIBarButtonItem alloc] initWithCustomView:self.barRightBtn];
        self.navigationItem.rightBarButtonItem = barBtn;

三十六.自定义ttf字体

    1.将xx.ttf字体库加入工程里;

 FAA2B395-A0C2-4E61-9AC0-9F1967DD0CAA.png

    2.在工程的xx-Info.plist文件中新添加一行Fonts provided by application,加上字体库的名称;

 FAE73710-9D67-4462-86A7-C6E4A4D60215.png

    3.引用字体库的名称,设置字体: [UIFontfontWithName:@"fontname" size:24];

 EEC4812B-9267-4E87-9DF5-66A6963991E0.png

    4.如果不知道字体名称,可以遍历字体进行查询:

         for(NSString *fontfamilyname in [UIFont familyNames])  
      {  
          NSLog(@"family:'%@'",fontfamilyname);  
          for(NSString *fontName in [UIFont fontNamesForFamilyName:fontfamilyname])  
          {  
              NSLog(@"\tfont:'%@'",fontName);  
          }  
          NSLog(@"-------------");  
      }  

三十七.导航栏字体颜色改变

有时候想改变某个控制器中状态栏的字体颜色,单纯的在控制器添加 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent],发现添加后无改变!这时候就需要设置另外一个属性!

    1.在 info.plist 中,将 View controller-based status bar appearance 设为 NO;
    2. 在对应控制器添加[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

三十八.类似于 modal 效果的弹出视图

        //初始化
       PopView *pop = [[PopView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, HEIGHT-150)];
        pop.bgImaView.image = [UIImage imageNamed:[NSString stringWithFormat:@"backgaund_%ld",(long)index]];
        [self.view addSubview:pop];

        //点击后frame改变,动画展示上滑 (类似于 btn 点击事件)
        [UIView animateWithDuration:0.5 animations:^{
            pop.frame = CGRectMake(0, 150, WIDTH, HEIGHT-150);
        }];

        //在点击改变frame,动画展示下滑
        [UIView animateWithDuration:0.5 animations:^{
            pop.frame = CGRectMake(0, HEIGHT, WIDTH, HEIGHT-150);
        }];

三十九.masonry 动画效果有时候不实现需要添加此方法  EA20C71D-FEA4-4BEF-A836-A8CA3C70964A.png

四十.设置手机声音震动

    #import <AudioToolbox>
    #import <UIKit>  
    - (void)vibrate   {    
          AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
     } 

四十一.设置上半部分圆角

    _titleLabel.layer.masksToBounds = YES;

    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:_titleLabel.bounds byRoundingCorners: UIRectCornerBottomLeft | UIRectCornerBottomRight cornerRadii: (CGSize){5.0f, 5.0f}].CGPath;

    _titleLabel.layer.mask = maskLayer;

四十二,图片的简单压缩

      1.  //背景视图 (此种压缩有白边出现)
        UIImageView *bgIma = [[UIImageView alloc] initWithFrame:BOUNDS];
        NSString *bgFile = [NSString stringWithFormat:@"%@/%@",[[NSBundle mainBundle] resourcePath,@"zsBg.png"]; //图片缓存处理
        UIImage *image = [[UIImage alloc] initWithContentsOfFile:bgFile];
        NSData *data = UIImageJPEGRepresentation(image, 1.0);
        bgIma.image = [UIImage imageWithData:data];
        [self addSubview:bgIma];

      2.封装方法
    - (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;
    }

    ((UIImageView *)view).image = [self imageWithImage:[UIImage imageNamed:self.notiArr[index]] scaledToSize:CGSizeMake(WIDTH-20, HEIGHT-64-10-180)] ;

四十三.横竖屏详细相关 传送门

四十四.后台无线定位  3754AB9E-4846-4668-ABB4-287C78C229A2.png

四十五.使用Xcode查找项目中的中文字符串,以方便实现国际化的需求

    1.打开”Find Navigator” (小放大镜模样 ---  放大镜)
    2.切换搜索模式到 “Find > Regular Expression”
    3.输入@"[^"]*[\u4E00-\u9FA5]+[^"\n]*?" (swift请去掉”@” 输入@"[^"]*[\u4E00-\u9FA5]+[^"\n]*?" 就好了)  

四十六.判断 iOS 系统版本

    _判断 iOS 系统版本大于10_

    #define IOS_VERSION_10 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_9_x_Max)?(YES):(NO)  

    _判断 iOS系统具体版本_

    1.预编译文件(.pch文件)定义
    #define iPHONEType struct utsname systemInfo;uname(&systemInfo);

    引用
    iPHONEType
    NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];

    2.[UIDevice currentDevice].systemVersion.floatValue  ,例如:

        if ([UIDevice currentDevice].systemVersion.floatValue < 7 xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed xss=removed> method: %s \n%s\n", self, [[[NSString stringWithUTF8String:__FILE__] lastPathComponent] UTF8String], __LINE__, __PRETTY_FUNCTION__, [[NSString stringWithFormat:(format), ##__VA_ARGS__] UTF8String] )
        #else
        #define SLog(format, ...)
        #endif 

    3. release模式下 系统自动注释slog , 以便于优化性能

四十九.筛选字符串(去除空格 换行符 回车符 首尾两端)

    - (NSString *)returnCustomString:(NSString *)string
    {
        [[[[[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] stringByReplacingOccurrencesOfString:@"/r" withString:@""] stringByReplacingOccurrencesOfString:@"/n" withString:@""] stringByReplacingOccurrencesOfString:@" " withString:@""] stringByReplacingOccurrencesOfString:@"/tab" withString:@""];

        return string;
    }

五十.数组和字典打印输出中文(新建一个分类,粘贴如下代码)

    @implementation NSDictionary (LOG)

    - (NSString *)descriptionWithLocale:(id)locale
    {
        // 1.定义一个可变的字符串, 保存拼接结果
        NSMutableString *strM = [NSMutableString string];
        [strM appendString:@"{\n"];
        // 2.迭代字典中所有的key/value, 将这些值拼接到字符串中
        [self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            [strM appendFormat:@"\t%@ = %@,\n", key, obj];
        }];
        [strM appendString:@"}"];

        // 删除最后一个逗号
        if (self.allKeys.count > 0) {
            NSRange range = [strM rangeOfString:@"," options:NSBackwardsSearch];
            [strM deleteCharactersInRange:range];
        }

        // 3.返回拼接好的字符串
        return strM;
    }

    @end

    @implementation NSArray (LOG)
    - (NSString *)descriptionWithLocale:(id)locale
    {
        // 1.定义一个可变的字符串, 保存拼接结果
        NSMutableString *strM = [NSMutableString string];
        [strM appendString:@"(\n"];
        // 2.迭代字典中所有的key/value, 将这些值拼接到字符串中
        [self enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            [strM appendFormat:@"\t%@,\n", obj];
        }];
        [strM appendString:@")\n"];

        // 删除最后一个逗号
        if (self.count > 0) {
            NSRange range = [strM rangeOfString:@"," options:NSBackwardsSearch];
            [strM deleteCharactersInRange:range];
        }

        // 3.返回拼接好的字符串
        return strM;
    }
    @end

五十一 . 十六进制转十进制

    - (NSString *)turn16to10:(NSString *)str {
        if (str.length>10) {
            str =[str substringFromIndex:str.length-10];
        }
        NSLog(@"字符=%@", str);
        unsigned long long result = 0;
        NSScanner *scanner = [NSScanner scannerWithString:str];
        [scanner scanHexLongLong:&result];
        NSString *tempInt =[NSString stringWithFormat:@"%llu", result];
        if (tempInt.length>7) {
            tempInt =[tempInt substringFromIndex:tempInt.length-7];
        }
        NSLog(@"数字=%@", tempInt);
        return tempInt;
    }
收藏
1
sina weixin mail 回到顶部