美文网首页iOS开发
记录iOS开发中的一些小技巧(一)

记录iOS开发中的一些小技巧(一)

作者: hanryChen | 来源:发表于2017-01-12 11:57 被阅读12次

    记录一下日常开发中用到的一些比较偏的知识

    GCC语法:
    self.navigationItem.rightBarButtonItem = ({
    
         UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithTitle:@"只看楼主" style:UIBarButtonItemStylePlain target:self action:@selector(onlyFollowLord:)];
    
         [rightItem setTitleTextAttributes:@{NSFontAttributeName:font(14.0)} forState:UIControlStateNormal];
    
         rightItem.tintColor = [UIColor textDarkGrayColor];
    
         rightItem;
    
    });
    这个问题严格上讲和Objective-C没什么太大的关系,这个是GNU C的对C的扩展语法 Xcode采用的Clang编译,Clang作为GCC的替代品,和GCC一样对于GNU C语法完全支持
    
    你可能知道if(condition)后面只能根一条语句,多条语句必须用{}阔起来,这个语法扩展即将一条(多条要用到{})语句外面加一个括号(), 这样的话你就可以在表达式中应用循环、判断甚至本地变量等。表达式()最后一行应该一个能够计算结果的子表达式加上一个分号(;), 这个子表达式作为整个结构的返回结果
    
    这个扩展在代码中最常见的用处在于宏定义中
    
    用runtime实现model序列化:
    
    - (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
         if (self = [super init]) {
    
              unsigned int count = 0;
    
              Ivar *ivar = class_copyIvarList([self class], &count);
    
              for (int i = 0; i<count; i++) {
    
                   Ivar iva = ivar[i];
    
                   const char *name = ivar_getName(iva);
    
                   NSString *strName = [NSString stringWithUTF8String:name];
    
                   id value = [aDecoder decodeObjectForKey:strName];
    
                   [self setValue:value forKey:strName];
              }
              free(ivar);
         }
         return self;
    }
    
    - (void)encodeWithCoder:(NSCoder *)aCoder {
    
         unsigned int count;
    
         Ivar *ivar = class_copyIvarList([self class], &count);
    
         for (int i=0; i < count; i++) {
    
              Ivar iv = ivar[i];
    
              const char *name = ivar_getName(iv);
    
              NSString *strName = [NSString stringWithUTF8String:name];
    
              id value = [self valueForKey:strName];
    
              [aCoder encodeObject:value forKey:strName];
    
         }
    
         free(ivar);
    
    }
    
    

    工程中的category(类目)里的方法不需要导入头文件就能执行,比如修改父类方法时,不导入头文件也能实现,如果要在category(类目)中加入新的方法或者属性才需要导入头文件。

    子线程中要修改外界的值需要用到线程锁,以防多处子线程同时修改同一值而造成闪退

    问题代码:

    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"haha", nil];
    
    //并行
    
    dispatch_queue_t queue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, DISPATCH_QUEUE_CONCURRENT);
    
    for (int i = 0 ;i < 2 ; i++ ) {
    
         dispatch_async(queue, ^{
    
                   if (array.count > 0) {
         
                   [array removeObjectAtIndex:0];
    
              }
    
         });
    
    }
    

    修改后的代码:

    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"haha", nil];
    
    //并行
    
    dispatch_queue_t queue = dispatch_queue_create(DISPATCH_QUEUE_PRIORITY_DEFAULT, DISPATCH_QUEUE_CONCURRENT);
    
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(1);
    
    for (int i = 0 ;i < 2 ; i++ ) {
    
         dispatch_async(queue, ^{
    
         dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    
         if (array.count > 0) {
    
              [array removeObjectAtIndex:0];
    
         }
    
         dispatch_semaphore_signal(semaphore);
    
         });
    
    }
    
    合成图片
    - (UIImage *)imageWithName:(NSString *)name size:(CGSize)size {
        //原图
        UIImage *image = [UIImage imageNamed:name];
        //背景图
        UIImage *backImage = [image imageWithTintColor:[UIColor colorWithHexString:@"#f39004"]];
        UIGraphicsBeginImageContextWithOptions(size, NO, image.scale);
        
        [backImage drawInRect:(CGRect){CGPointZero,size}];
        [image drawInRect:(CGRect){(size.width - image.size.width) / 2,(size.height - image.size.height) / 2,image.size.width,image.size.height}];
        //合成
        UIImage *newsImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        return newsImage;
    }
    
    用GCD倒计时
    -(void)startTimerBackZero:(NSInteger)time {
        __block NSInteger timeout = time; //倒计时时间
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
        dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1ull*NSEC_PER_SEC, 0); //每秒执行
        dispatch_source_set_event_handler(_timer, ^{
            if(timeout<=0){ //倒计时结束,关闭
                dispatch_source_cancel(_timer);
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    self.enabled = YES;
                    [self setTitle:@"重发验证码" forState:UIControlStateNormal]; 
                });
            }else{ 
                self.enabled = NO;
                NSString *strTime = [NSString stringWithFormat:@"%ld秒后重获",(long)timeout];
                dispatch_async(dispatch_get_main_queue(), ^{
                    //设置界面的按钮显示 根据自己需求设置
                    [self setTitle:strTime forState:UIControlStateNormal];
                });
                timeout--; 
            }
        });
        dispatch_resume(_timer);
    }
    
    生成二维码
    // 创建过滤器
        CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
        // 恢复默认
        [filter setDefaults];
        NSData *data = [self.shopURL dataUsingEncoding:NSUTF8StringEncoding];
        [filter setValue:data forKeyPath:@"inputMessage"];
        // 获取输出的二维码
        CIImage *outputImage = [filter outputImage];
        // 将CIImage转换成UIImage,并放大显示
        outputImage = [outputImage imageByApplyingTransform:CGAffineTransformMakeScale(150, 150)];
        [UIImage imageWithCIImage:outputImage];
    
    Autolayout的两个属性的使用说明
    640254-97c4b2c919ac69d8.png.jpeg

    “Content Compression Resistance Priority”,也叫内容压缩阻力优先级(小名:别挤我),该优先级越高,则越晚轮到被压缩。

    “Content Hugging Priority”,也叫内容紧靠优先级(小名:别扯我),该优先级越高,这越晚轮到被拉伸。

    渐变颜色
    - (CAGradientLayer *)shadowAsInverse {
        CAGradientLayer *layer = [[CAGradientLayer alloc] init];
        CGRect rect = _imageView.bounds;
        layer.frame = rect;
        layer.colors = [NSArray arrayWithObjects:(id)[UIColor yellowColor].CGColor,(id)[UIColor redColor].CGColor, nil];
        layer.startPoint = CGPointMake(0, 0);
        layer.endPoint = CGPointMake(1, 0);
        layer.cornerRadius = 64;
        return layer;
    }
    

    相关文章

      网友评论

        本文标题:记录iOS开发中的一些小技巧(一)

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