美文网首页
iOS小知识

iOS小知识

作者: 音吹 | 来源:发表于2016-07-20 17:12 被阅读33次

1. 程序进入后台继续执行代码操作

在AppDelegate文件中创建一个属性
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundUpdateTask;

并且在下面这个方法中实现你想要执行的代码

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [self beingBackgroundUpdateTask];
    
    NSLog(@"你想要执行的代码");
    
    [self endBackgroundUpdateTask];

}

这是下面的两个方法的实现

- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
    [self endBackgroundUpdateTask];
    }];
}
- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask:self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

2. 关键字

nullable:表示可以为空;
nonnull:表示不能为空;
null_resettable: get:不能返回为空,set可以为空;选择重写set或者get;
_Null_unspecified:不确定是否为空,暂时没发现有啥用;

  • 1__kindof:表示当前类或者它的子类;
  • 2__covariant(协变):用于泛型数据强转类型,可以向上强转,子类可以转成父类;
  • 3__contravariant(逆变):用于泛型数据强转类型,可以向下强转,父类可以转成子类;
@property (nonatomic,strong, nullable) NSString * name;
@property (nonatomic,strong) NSString * _Nullable stu;
@property (nonatomic,strong, null_resettable) NSString * name;
@property (nonatomic,strong) NSString * _Null_unspecified name;

3. 下载苹果官方字体库

地址:http://www.developer.apple.com/library/ios/#samplecode/DownloadFont/Listings/DownloadFont_ViewController_m.html


4. -w:禁止所有的编译警告;

 -Wno-unused-variable:只禁止未使用变量的  

的编译警告;

5. 使用函数式指针忽略警告


忽略警告:
#pragma clang diagnostic push 
#pragma clang diagnostic ignored "-Warc-performSelector-leaks" 
        [_target performSelector:_action withObject:self];
#pragma clang diagnostic pop
如果需要忽视的警告有多处,可以定义一个宏:
#define IgnorePerformSelectorLeakWarning(Stuff) \  
do {\ _Pragma("clang diagnostic push") \ 
_Pragma("clang diagnostic ignored \
"-Warc-performSelector-leaks\"") \ 
Stuff; \ 
_Pragma("clang diagnostic pop") \ 
} while (0)
使用方法:
IgnorePerformSelectorLeakWarning( [_target performSelector:_action withObject:self]);

6.HTML字符转NSString

 //1.html转string
    NSString * htmlString = @"<html><body> Some html string \n <font size=\"13\" color=\"red\">This is some text!</font> </body></html>";
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[htmlString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    UILabel * myLabel = [[UILabel alloc] initWithFrame:self.view.bounds];
    myLabel.attributedText = attrStr;
    [self.view addSubview:myLabel];

7.判断是是否为PNG/GIF图片

//通过图片Data数据第一个字节 来获取图片扩展名
- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    switch (c) {
        case 0xFF:
            return @"jpeg";
        case 0x89:
            return @"png";
        case 0x47:
            return @"gif";
        case 0x49:
        case 0x4D:
            return @"tiff";
        case 0x52:
            if ([data length] < 12) {
                return nil;
            }
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                return @"webp";
            }
            return nil;
    }
    return nil;
}
  • 使用方法
    //假设这是一个网络获取的URL
    NSString *path = @"http://pic.rpgsky.net/images/2016/07/26/3508cde5f0d29243c7d2ecbd6b9a30f1.png";
    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:path]];
    //调用获取图片扩展名
    NSString *string = [self contentTypeForImageData:data];
    //输出结果为 png
    NSLog(@"%@",string);

8.设置圆角的几种方法

  • 1.绘图
/** 设置圆形图片(放到分类中使用) */
- (UIImage *)cutCircleImage {
    UIGraphicsBeginImageContextWithOptions(self.size, NO, 0.0);
    // 获取上下文
    CGContextRef ctr = UIGraphicsGetCurrentContext();
    // 设置圆形
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextAddEllipseInRect(ctr, rect);
    // 裁剪
    CGContextClip(ctr);
    // 将图片画上去
    [self drawInRect:rect];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
  • 1.1绘图传参
@implementation UIImage (RoundedCorner)
- (UIImage *)imageWithRoundedCornersAndSize:(CGSize)sizeToFit andCornerRadius:(CGFloat)radius
{
    CGRect rect = (CGRect){0.f, 0.f, sizeToFit};
    UIGraphicsBeginImageContextWithOptions(sizeToFit, NO, UIScreen.mainScreen.scale);
    CGContextAddPath(UIGraphicsGetCurrentContext(),
                     [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:radius].CGPath);
    CGContextClip(UIGraphicsGetCurrentContext());
    [self drawInRect:rect];
    UIImage *output = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return output;
}
  • 2.圆角封装
    UIView * circleView = [UIView new];
    circleView.frame = CGRectMake(0, 0, 100, 100);
    circleView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"image"]];
    [CircleImagePic getCircleImage:circleView cornerRadius:circleView.bounds.size.width/2];
    [self.view addSubview:circleView];

创建NSObject

+ (void)getCircleImage:(UIView *)circleView cornerRadius:(NSInteger)cornerRadius
{
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:circleView.bounds byRoundingCorners:UIRectCornerAllCorners cornerRadii:CGSizeMake(cornerRadius, 0)];
    CAShapeLayer * layer = [[CAShapeLayer alloc] init];
    layer.frame = circleView.bounds;
    layer.path = path.CGPath;
    circleView.layer.mask = layer;
    circleView.layer.cornerRadius = cornerRadius;
    circleView.layer.masksToBounds = YES;

}
  • 3.带缓存机制的圆角
    UIView * cacheImage = [UIView new];
    cacheImage.frame = CGRectMake(200, 0, 100, 100);
    cacheImage.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"image"]];
    
    cacheImage.layer.masksToBounds = YES;
    cacheImage.layer.cornerRadius = cacheImage.bounds.size.width/2;
    cacheImage.layer.shouldRasterize = YES;
    cacheImage.layer.rasterizationScale = [UIScreen mainScreen].scale;
    [self.view addSubview:cacheImage];

9.移动文件


//    /Users/apple/Desktop/初始文件夹/Myfile

    //文件在哪个地方(文件夹)
    NSString *form = @"/Users/apple/Desktop/初始文件夹";
    //要剪切到什么地方
    NSString *to = @"/Users/apple/Desktop/移动到这里";
    
    NSFileManager *manager = [NSFileManager defaultManager];
    NSArray *subpaths =  [manager subpathsAtPath:form];
    NSDirectoryEnumerator *enumer = [manager enumeratorAtPath:to];
//    NSDirectoryEnumerator *enumer = [manager directoryContentsAtPath:form];
    
    for (NSDirectoryEnumerator *en in enumer) {
        NSLog(@"%@",en);
    }

    //创建队列(并发队列)
    dispatch_queue_t queue = dispatch_queue_create("com.downloadqueue", DISPATCH_QUEUE_CONCURRENT);
    
    NSInteger count = [subpaths count];
    dispatch_apply(count, queue, ^(size_t index) {
        
        NSString *subpath = subpaths[index];
        
        NSString *fullPath = [form stringByAppendingPathComponent:subpath];
        
        //拼接目标文件全路径
        NSString *fileName = [to stringByAppendingPathComponent:subpath];
        
        //剪切操作
        [manager moveItemAtPath:fullPath toPath:fileName error:nil];
        
    });

10.NSString与NSData互转

- (NSString *)hexStringFromData:(NSData*)data{  
    return [[[[NSString stringWithFormat:@"%@",data]  
              stringByReplacingOccurrencesOfString: @"<" withString: @""]  
             stringByReplacingOccurrencesOfString: @">" withString: @""]  
            stringByReplacingOccurrencesOfString: @" " withString: @""];  
}  
- (NSData*)dataFormHexString:(NSString*)hexString{  
    hexString=[[string uppercaseString] stringByReplacingOccurrencesOfString:@" " withString:@""];  
    if (!(hexString && [hexString length] > 0 && [hexString length]%2 == 0)) {  
        return nil;  
    }  
    Byte tempbyt[1]={0};  
    NSMutableData* bytes=[NSMutableData data];  
    for(int i=0;i<[hexString length];i++)  
    {  
        unichar hex_char1 = [hexString characterAtIndex:i]; ////两位16进制数中的第一位(高位*16)  
        int int_ch1;  
        if(hex_char1 >= '0' && hex_char1 <='9')  
            int_ch1 = (hex_char1-48)*16;   //// 0 的Ascll - 48  
        else if(hex_char1 >= 'A' && hex_char1 <='F')  
            int_ch1 = (hex_char1-55)*16; //// A 的Ascll - 65  
        else  
            return nil;  
        i++;  
          
        unichar hex_char2 = [hexString characterAtIndex:i]; ///两位16进制数中的第二位(低位)  
        int int_ch2;  
        if(hex_char2 >= '0' && hex_char2 <='9')  
            int_ch2 = (hex_char2-48); //// 0 的Ascll - 48  
        else if(hex_char2 >= 'A' && hex_char2 <='F')  
            int_ch2 = hex_char2-55; //// A 的Ascll - 65  
        else  
            return nil;  
          
        tempbyt[0] = int_ch1+int_ch2;  ///将转化后的数放入Byte数组里  
        [bytes appendBytes:tempbyt length:1];  
    }  
    return bytes;  
}  

相关文章

  • 两年iOS经验之你忽略的小知识点

    两年iOS经验之你忽略的小知识点 两年iOS经验之你忽略的小知识点

  • ios-收集一些自认为有用的小知识

    ios-收集一些自认为有用的小知识 ios-收集一些自认为有用的小知识

  • iOS 知识-常用小技巧大杂烩

    iOS 知识-常用小技巧大杂烩 - 简书

  • iOS 小知识

    UILabel 通过文字计算宽高 UILable *lable=[UILable alloc]init]; lab...

  • iOS小知识

    刷榜 刷榜:指通过技术手段提高APP在iTunes App Store内排行榜的排名,包括iPhone免费排行榜;...

  • ios 小知识

    1.添加了IQKeyboardManager库之后,有些页面在收回键盘时会上移导致无法返回,检查代码后发现是进入页...

  • iOS 小知识

    调整tabbar文字位置 UIOffsetMake(0, -2)第一个参数是设置水平偏移,第二个参数是设置垂直偏移...

  • ios小知识

    1,常用网络框架默认网络请求超时时长 默认的网络请求超时时长 ASI 是10秒 苹果官方是60秒 SDWebIma...

  • ios小知识

    数组中的指针 int array[3] = {11,22,33} • &array[0] 可看做是一个指针,指向...

  • iOS 小知识

    1、iOS8 下,tableView要实现左滑删除,必须要实现这个代理方法,哪怕里面什么都没写: 2、iOS8 下...

网友评论

      本文标题:iOS小知识

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