GXiOS

iOS开发--Foundation框架

2019-05-20  本文已影响6人  Caesar_62dd

Foundation框架介绍

NSString基本概念

直接读写文件中的字符

// 用来保存错误信息
NSError *error = nil;
//路径
NSString *path = @"/Users/gaoxiong/Data/GaoCode/CPractcies/Day17/文件读写/gx.txt";

// 读取文件内容
NSString *str = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];


// 如果有错误信息
if (error) {
    NSLog(@"读取失败, 错误原因是:%@", [error localizedDescription]);
} else { // 如果没有错误信息
    NSLog(@"读取成功, 文件内容是:\n%@", str);
}
NSString *str = @"gx";
// atomically 如果传入YES, 字符串写入文件的过程中如果没有写完, 那么不会生成文件
//            如果传入NO, 字符串写入文件的过程中如果没有写完, 会生成文件
BOOL flag = [str writeToFile:@"/Users/gaoxiong/Desktop/gx.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
if (flag == 1)
{
    NSLog(@"写入成功");
}

NSURL

        //保存错误信息
        NSError *error = nil;
        //本机地址省略主机域名
        NSString *path = @"file:///Users/gaoxiong/Desktop/gx.txt";
        //方法一:URLWithString
        NSURL *url = [NSURL URLWithString: path];
        //读取指定URL文件信息
        NSString *str = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
        //输出
        NSLog(@"%@",str);
        
        //URL中带有中文
        NSString *path2 = @"file:///Users/gaoxiong/Desktop/齐天大圣/zbj.txt";
        //对中文进行百分号编码
        path2 = [path2 stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
        //创建URL:URLWithString
        NSURL *url2 = [NSURL URLWithString:path2];
        //读取
        NSString *str2 = [NSString stringWithContentsOfURL:url2 encoding:NSUTF8StringEncoding error:&error];
        //输出
        NSLog(@"%@",str2);
        
        //方法二:fileURLWithPath,方法中包含t协议头file://
        NSURL *url3 = [NSURL fileURLWithPath:@"/Users/gaoxiong/Desktop/齐天大圣/zbj.txt"];
        NSString *str4 = [NSString stringWithContentsOfURL:url3 encoding:NSUTF8StringEncoding error:&error];
        //判断读取成功之后输出
        if (error) {
            NSLog(@"读取失败,错误原因是:%@",[error localizedDescription]);
        }else{
            NSLog(@"读取成功,文件内容是:\n%@",str4);
        }
                //写入URL
        NSString *str5 = @"西风烈,长空雁叫霜晨月。霜晨月,马蹄声碎,喇叭声咽;雄关漫道真如铁,而今迈步从头越。从头越,苍山如海,残阳如血。";
        [str5 writeToURL:url3 atomically:YES encoding:NSUTF8StringEncoding error: nil];
        
  • 如果访问本机资源,创建URL的时候,建议使用fileURLWithPath方法创建

  • URL不支持中文,如果URL中包含中文,那么无法访问;

  • 但是如果通过fileURLWithPath方法创建URL,系统内部会自动对URL中的中文进行处理,可以访问.

  • 如果URL中包含中文,又不能通过fileURLWithPath创建,则必须在创建URL之前相对字符串进行中文处理,进行百分号编码

  • stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]


2.NSRange基本概念

typedef struct _NSRange {
    NSUInteger location;
    NSUInteger length;
} NSRange;
// NSUInteger的定义
typedef unsigned int NSUInteger;

3.NSRange的创建

NSRange range;
range.location = 7;
range.length = 3;

1.字符串的截取

              
            //字符串截取:substringWithRange
        NSString *str = @"<head>iPhone</head>";
            //OC提供的结构体,一般都可以t用NSMAKEXXX来创建
            //        NSRange range = NSMakeRange(6, 6);
            //1.动态获取截取的起止位置
        NSUInteger location = [str rangeOfString:@">"].location + 1;
            //2.动态获取截取长度
            //2.1反向查找
            //        NSUInteger length = [str rangeOfString:@"<" options:NSBackwardsSearch].location -location;
            //2.2正向查找
        NSUInteger length = [str rangeOfString:@"</"].location -location;
        NSLog(@"\nlocation = %lu, length = %lu", location, length);
        NSRange range = NSMakeRange(location, length);
        NSString *newStr = [str substringWithRange:range];
        NSLog(@"newStr = %@",newStr);
        
        
            //字符串截取2:- (NSString *)substringFromIndex:(NSUInteger)from;
            //字符串截取3:- (NSString *)substringToIndex:(NSUInteger)to;
            //截取过程:<head>iPhone</head>--->iPhone</head>---->iPhone
        NSLog(@"  str   = %@", str);
        NSUInteger location2 = [str rangeOfString:@">"].location + 1;
        NSString *newstr2 = [str substringFromIndex:location2];
        NSLog(@"newStr2 = %@",newstr2);
        location2 = [newstr2 rangeOfString:@"</"].location ;
        newstr2 = [newstr2 substringToIndex:location2];
        NSLog(@"newStr2 = %@", newstr2);
        
        /* 输出
         location = 6, length = 6
         newStr = iPhone
         str   = <head>iPhone</head>
         newStr2 = iPhone</head>
         newStr2 = iPhone
         */

字符串替换

        NSString *str = @"  www.baidu.com   ";
        NSLog(@"str = %@", str);
        
        //字符串替换
        //- (NSString)stringByReplacingOccurrencesOfString:(NSString )target withString:(NSString *)replacement;
        NSString *newStr = [str stringByReplacingOccurrencesOfString:@"baidu" withString:@"30414
        NSLog(@"newStr = %@", newStr);
        
        //去除首位空格: whitespaceCharacterSet
        //- (NSString)stringByTrimmingCharactersInSet:(NSCharacterSet)set;
        NSCharacterSet *set = NSCharacterSet.whitespaceCharacterSet;
        newStr = [newStr stringByTrimmingCharactersInSet:set];
        NSLog(@"newStr = |%@|", newStr);
        
        //去除首尾某个字符: characterSetWithCharactersInString
        NSString *str1 = @"***http://www.china.***com***";
        NSLog(@"str1 = %@", str1);
        NSString *newStr1 = [str1 stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"*"]];
        NSLog(@"newStr1 = %@", newStr1);
        /*
         输出结果:
                str =   www.baidu.com
                newStr =   www.qq.com
                newStr = |www.qq.com|
                str1 = ***http://www.china.***com***
                newStr1 = http://www.china.***com
         */

字符串与路径、扩展名


          //NSString与路径PathComponent
            //1.判断是否是一个绝对路径:isAbsolutePath
            //本质:判断是否以 / 开头
        NSString *str = @"/Users/gaoxiong/Desktop/gx.txt";
        if ([str isAbsolutePath]) {
            NSLog(@"是一个绝对路径");
        }else{
            NSLog(@"不是一个绝对路径");
        }
        
            //2.获取文件路径最后一个目录:lastPathComponent
        //本质:获取最后一个 / 之后的文件名
        NSString *newStr = [str lastPathComponent];
        NSLog(@"%@", newStr);
        
            //3.删除文件路径中的最后一个路径:stringByDeletingPathExtension
            //文件有扩展名只删除了扩展名
        newStr = [str stringByDeletingPathExtension];
        NSLog(@"%@", newStr);
        
            //4.在文件路径最后增加一个目录
            //本质:在字符串的末尾加上一个 / 和指定内容
            //自动判断更改路径格式:只保留一个/
        newStr = [newStr stringByAppendingPathComponent:@"/txt"];
        NSLog(@"%@", newStr);
        
            //文件与扩展名PathExtension
        NSString *str1 = @"/Users/gaoxiong/Desktop/gx.txt";
            //1.获取文件扩展名:pathExtension
        newStr = [str1 pathExtension];
        NSLog(@"%@", newStr);
            //2.删除文件扩展名:stringByDeletingPathExtension
        str1 = [str1 stringByDeletingPathExtension];
        NSLog(@"%@", str1);
            //3.添加扩展名
        str1 = [str1 stringByAppendingPathExtension:@".txt"];
        NSLog(@"%@", str1);
        

字符串与基本数据类型转换

        //返回index对应位置的字符:characterAtIndex:(NSUInteger) index
        NSString *str = @"I love peace!";
        unichar c = [str characterAtIndex:0];
        NSLog(@"%c", c);
        //字符串长度length属性
        NSUInteger length = str.length;
        NSLog(@"length = %lu", length);
        //字符串转换为基本数据类型
        NSString *str1 = @"12";
        NSUInteger num = [str1 intValue];
        double d = [str1 doubleValue];
        float f = [str1 floatValue];
        int i = [str1 intValue];
        NSLog(@"nsuinteger = %lu, float = %f, double = %lf, int = %i ", num, f, d, i);
        //NSString转换为C语言字符串
        const char *cStr = [str UTF8String];
        NSLog(@"%s", cStr);
        //C语言字符串转换为NSString
        NSString *str2 = [NSString stringWithUTF8String:cStr];
        NSLog(@"%@", str2);

NSMutableString基本概念


NSMutableString常用方法


1.NSMutableString常用方法

        //多种初始化方式
        NSMutableString *strM = [[NSMutableString alloc] init];
        NSMutableString *strM2 = [NSMutableString stringWithFormat:@"abc"];
        NSMutableString *strM3 = [NSMutableString stringWithString:@"www.qq.com"];
        
        
        //增加: appendString
        [strM appendString:@"zhubajie"];
        NSLog(@"%@", strM);
        //增加:appendFormat
        [strM appendFormat:@" is lulu "];
        NSLog(@"%@", strM);
        
        //删除
        //在开发中经常使用rangeOfString和deleteCharactersInRange配合删除指定字符串
        NSRange range = [strM3 rangeOfString:@"www."];
        [strM3 deleteCharactersInRange:range];
        NSLog(@"%@", strM3);
        
        //插入
        [strM2 insertString:@"520" atIndex:0];
        NSLog(@"%@", strM2);
        [strM insertString:@"zhubajie" atIndex:0];
        
        //修改
        //count: 替换数量
        //options:搜索方式
        //range:搜索范围
       NSUInteger count =  [strM replaceOccurrencesOfString:@"zhubajie" withString:@"xiaokeai" options:0 range:NSMakeRange(0, strM.length)];
        NSLog(@"%@,\ncount = %lu",strM,count);
        

2.字符串使用注意事项

NSMutalbeString *s1 = @”gx”;
// 会报错
[strM insertString:@"my name is " atIndex:

1.NSArray的基本概念


2.NSArray的创建方式和使用

        //NSArray 创建方式
        NSURL *url = [NSURL fileURLWithPath:@"/Users/gaoxiong/Desktop/gx.txt"];
        Person *lulu = [Person personWithName:@"璐璐"];
        NSObject *obj = [NSObject new];
        
        NSArray *arr = [[NSArray alloc] initWithObjects:lulu,obj, nil];
        NSArray *arr2 = [NSArray arrayWithObject:@"Lulu"];
        NSArray *arr3 = [NSArray arrayWithObjects:@"gx",@"pig",@"xiaokeai", nil];
        NSArray *arr4 = [NSArray arrayWithContentsOfURL:url];
        //数组的文件导入
        NSArray *arr5 = [NSArray arrayWithContentsOfFile:@"/Users/gaoxiong/Desktop/gx.plist"];
        NSArray *arr6 = [NSArray arrayWithArray:arr3];
        //数组的文件导出
        //writeToFile 只能导出Foundation框架里的类, 自定义的类导出失败.需要用其他方法
        NSArray *arr7 = [NSArray arrayWithObjects:@"zhubajie",@"sunwukong",@"tangsanzang",@"shawujing", @"齐天大圣",nil];
        BOOL flag0 = [arr7 writeToFile:@"/Users/gaoxiong/Desktop/gx.xml" atomically:YES];
        NSLog(@"flag0 = %i", flag0);
        NSLog(@"arr4 = %@",arr4);
        NSLog(@"arr5 = %@",arr5);
        NSLog(@"arr6 = %@",arr6);
        
        //使用
        //集合元素的个数
        NSUInteger count = arr3.count;
        NSLog(@"count = %lu", count);
        //获取index位置的元素
        id obj2 = [arr2 objectAtIndex:0];
        NSLog(@"%@",obj2);
        //是否包含某个元素
        BOOL flag = [arr containsObject:lulu];
        NSLog(@"%i", flag);
        //返回最后一个元素
        id last = [arr5 lastObject];
        NSLog(@"last = %@", last);
        //返回第一个元素
        id first = [arr7 firstObject];
        NSLog(@"first = %@", first);
        //查找anObject元素在数组中的位置(如果找不到,返回-1)
        NSUInteger index = [arr7 indexOfObject:@"sunhukong"];
        NSLog(@"index = %lu", index);
        //在range范围内查找anObject元素在数组中的位置
        NSUInteger index2 = [arr7 indexOfObject:@"choubaguai" inRange:NSMakeRange(0, 3)];
        NSLog(@"index2 = %lu", index2);

3.NSArray 的使用注意事项

    NSArray *arr = [NSArray arrayWithObjects:@"gx", nil ,@"lulu", nil];
    NSLog(@"%@", arr);
输出结果:
(
    gx
)

4.NSArray的简写形式

NSArray 遍历

        //下标遍历
        NSArray *arr = [NSArray arrayWithContentsOfFile:@"/Users/gaoxiong/Desktop/gx.txt"];
        for (int i = 0; i < arr.count; i++) {
            NSString *str = arr[I];
            NSLog(@"arr[%i] = %@", i, str);
        }
        
        //快速遍历
        Person *p1 = [Person personWithName:@"大头"];
        Person *p2 = [Person personWithName:@"大大头"];
        Person *p3 = [Person personWithName:@"大大大头"];
        Person *p4 = [Person personWithName:@"大大大大头"];
        Person *p5 = [Person personWithName:@"大大大大大头"];

        //OC数组使用增强for循环
        //逐个取出集合中元素,赋值给 *p
        NSArray *arr2 = @[p1, p2, p3, p4, p5];
        for (Person *p in arr2) {
            [p say];
        }

        //OC数组迭代器来遍历
        //使用block遍历
        //每取出一个元素调用一次block
        //每次调用block都会将元素及其index传递给我们
        //obj 代表当前元素, idx就是当前索引
        //stop 是控制循环结束
        [arr2 enumerateObjectsUsingBlock:^(Person *obj, NSUInteger idx, BOOL *stop){
            if (idx == 1) {
                *stop = YES;
            }
            Person *p = obj;
            [p say];
        }];
        
        //让所有元素执行同一方法(给所有元素发消息)
        [arr2 makeObjectsPerformSelector:@selector(say)];
        [arr2 makeObjectsPerformSelector:@selector(sayWithName:) withObject:@"八戒!"];
        

NSArray排序

        //Foundation排序
        //sortedArrayUsingSelector compare: 必须是oc对象
        NSArray *arr = @[@10, @20, @30, @40, @9];
        NSArray *newArr = [arr sortedArrayUsingSelector:@selector(compare:)];
        NSLog(@"排序前: \n%@", arr);
        NSLog(@"排序后: \n%@", newArr);
                
                //自定义排序
        //按照人的年龄排序
        Person *p1 = [Person personWithName:@"大头" andAge:10];
        Person *p2 = [Person personWithName:@"大大头" andAge:30];
        Person *p3 = [Person personWithName:@"大大大头" andAge:20];
        Person *p4 = [Person personWithName:@"大大大大头" andAge:9];
        Person *p5 = [Person personWithName:@"大大大大大头" andAge:8];
        NSArray *arr2 = @[p1,p2,p3,p4,p5];
        NSArray *newArr2 =[arr2 sortedArrayWithOptions:NSSortStable usingComparator:^NSComparisonResult(Person *obj1,Person *obj2) {
            return  obj1.age < obj2.age;
        }];
        NSLog(@"排序前:%@", arr2);
        NSLog(@"排序后:%@", newArr2);

NSArray 与字符串

        //数组转字符串componentsJoinedByString
        NSArray *arr = [NSArray arrayWithObjects:@"zhubajie",@"sunhukong",@"tangsanzang",@"shawujing", @"齐天大圣",nil];
        NSString *str = [arr componentsJoinedByString:@"-"];
        NSLog(@"str = %@", str);
        
        //字符串切割(字符串转数组)componentsSeparatedByString
        NSArray *newAra = [str componentsSeparatedByString:@"-"];
        NSLog(@"%@", newAra);

NSMutableArray基本概念


1.NSMutableArray介绍


2.NSMutableArray基本用法

        //NSMUtableArray的创建方式
        NSMutableArray *arrM0 = [NSMutableArray arrayWithObjects:@"ll",@"ww",@6, nil];
        //创建一个空的可变数组
        NSMutableArray *arrM = [NSMutableArray array];
        //添加元素
        [arrM addObject:@"gx"];
        [arrM addObjectsFromArray:@[@"lkl", @"hxh"]];
        //将整个数组当作一个元素添加到数组
        [arrM addObject:@[@"lkl", @"hxh"]];
        //插入元素
        [arrM insertObject:@"NNNNNN" atIndex:0];
        NSLog(@"%@",arrM);
        [arrM insertObjects:arrM0 atIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, 3)]];
        NSLog(@"%@",arrM);

        //如何删除 
        [arrM removeObject:@"NNNNNN"];
        [arrM removeObjectAtIndex:1];
        [arrM removeLastObject];
        NSLog(@"%@", arrM);
        
        //替换
        [arrM replaceObjectAtIndex:1 withObject:@"xx"];
                //简单写法
        arrM[0] = @"gg";
        NSLog(@"%@", arrM);

        //交换
        [arrM exchangeObjectAtIndex:0 withObjectAtIndex:1];
        NSLog(@"%@", arrM);


3.NSMutableArray 错误用法

NSMutableArray *array = @[@"gx", @"璐璐", @"jjj"];
// 报错, 本质还是不可变数组
[array addObject:@“Peter”];

NSDictionary基本概念

NSDictionary的创建

+ (instancetype)dictionary;
+ (instancetype)dictionaryWithObject:(id)object forKey:(id <NSCopying>)key;
+ (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
+ (id)dictionaryWithContentsOfFile:(NSString *)path;
+ (id)dictionaryWithContentsOfURL:(NSURL *)url;
            //1.如何创建dictionaryWithObject:forKey:
        NSDictionary *dict0 = [NSDictionary dictionaryWithObject: @"gx" forKey:@"name"];
        NSString *name = [dict0 objectForKey:@"name"];
        NSLog(@"name = %@", name);
            //创建dictionaryWithObjects:forKeys:
        NSDictionary *dict1 = [NSDictionary dictionaryWithObjects:@[@"gx", @"18", @"1.85"] forKeys:@[@"name", @"ages", @"height"]];
        NSLog(@"%@, %@, %@",[dict1 objectForKey:@"name"], [dict1 objectForKey:@"ages"], [dict1 objectForKey:@"height"]);
            //快速创建
        NSDictionary *dict2 = @{@"name":@"gx",@"ages":@"18", @"height":@"1.85"};
        NSLog(@"%@, %@, %@",dict2[@"name"], dict2[@"ages"], dict2[@"height"]);
        
            //2.字典的遍历
            //2.1获取字典中的key(键)和value(值)的个数
        NSDictionary *dict3 = @{@"name":@"gx",@"ages":@"18", @"height":@"1.85"};
        for (int i = 0; i < dict3.count; i++) {
            NSArray *keys = [dict3 allKeys];
            NSString *key = keys[I];
            NSString *value = dict3[key];
            NSLog(@"key = %@, value = %@", key, value);
            
                //2.2forIn遍历字典,将所有的key赋值给前面的Obj
        for (NSString *key in dict3) {
            NSLog(@"%@", key);
            NSString *value = dict3[key];
            NSLog(@"key = %@, value = %@", key, value);
        }
            
                //2.3迭代器Block
        [dict3 enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            NSLog(@"key = %@, value = %@", key, value);
        }];
            
                //3.字典文件读写
        [dict3 writeToFile:@"/Users/gaoxiong/Desktop/GXInfo.plist" atomically:YES];
        NSDictionary *dict4 = [NSDictionary dictionaryWithContentsOfFile:@"/Users/gaoxiong/Desktop/GXInfo.plist"];

        

NSMutableDictionary

        //1.创建一个空的字典
        NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
        NSLog(@"%@", dictM);
        //2.添加
        [dictM setObject:@"gx" forKey:@"name"];
        //2.1简写
        dictM[@"ages"] = @"18";
        //3.获取
        NSLog(@"name = %@", dictM[@"name"] );
        //4.删除
        [dictM removeObjectForKey:@"ages"];
        //4.1多个删除
        [dictM removeObjectsForKeys:@[@"ages", @"name"]];
        //5.修改
        [dictM setObject:@"19" forKey:@"ages"];
        
        /******************************注意*****************************/
        //1.不能用@{}来创建一个可变的字典
        //2.如果是不可变数组,那么key不能相同
        //2.1在不可变数组中出现同名的key,那么后面的key不会保存
        //2.2在可变数组中出现同名的key,那么后面的key会覆盖前面的key

2.NSDictionary和NSArray对比

常见的结构体

1.NSPoint和CGPoint

typedef CGPoint NSPoint;

CGPoint的定义
struct CGPoint {
  CGFloat x;
  CGFloat y;
};
typedef struct CGPoint CGPoint;
typedef double CGFloat;

2.NSSize和CGSize

typedef CGSize NSSize;

CGSize的定义
struct CGSize {
  CGFloat width;
  CGFloat height;
};
typedef struct CGSize CGSize;

3.NSRect和CGRect

typedef CGRect NSRect;

CGRect的定义
struct CGRect {
  CGPoint origin;
  CGSize size;
};
typedef struct CGRect CGRect;

4.常见的结构体使用注意

NSNumber

1.NSNumber基本概念

nsnumber1.png nsnumber2.png

2.NSNumber的创建

+ (NSNumber *)numberWithInt:(int)value;
+ (NSNumber *)numberWithDouble:(double)value;
+ (NSNumber *)numberWithBool:(BOOL)value;

3.NSNumber对象转换

- (char)charValue;
- (int)intValue;
- (long)longValue;
- (double)doubleValue;
- (BOOL)boolValue;
- (NSString *)stringValue;
- (NSComparisonResult)compare:(NSNumber *)otherNumber;
- (BOOL)isEqualToNumber:(NSNumber *)number;

NSValue


1.NSValue基本概念


2. 常见结构体的包装

+ (NSValue *)valueWithPoint:(NSPoint)point;
+ (NSValue *)valueWithSize:(NSSize)size;
+ (NSValue *)valueWithRect:(NSRect)rect;
- (NSPoint)pointValue;
- (NSSize)sizeValue;
- (NSRect)rectValue;

3.任意数据的包装

        typedef struct {
            int age;
            char *name;
            double height;
        }person;
        person p1 = {10 ,"gx", 1.85};
        //自定义结构体转NS对象
        NSValue *pValue = [NSValue valueWithBytes:&p1 objCType:@encode(person)];
        NSArray *arr = @[pValue];
        NSLog(@"%@", arr);
        //取出nNSValue的值
        person res;
        [pValue getValue:&res];
        NSLog(@"age = %i, name = %s, height = %0.2f", res.age, res.name, res.height);

NSDate

        //1.NSDate创建和基本概念
        NSDate *now = [NSDate date];//获取当前时间
        NSLog(@"now = %@", now);
        //在now基础上追加多少秒
        NSDate *date = [now dateByAddingTimeInterval:10];
        NSLog(@"date = %@", date);
        //获取所在时区
        NSTimeZone *zone = [NSTimeZone systemTimeZone];
        //获取当前时区和指定时间的时间差
        NSInteger seconds = [zone secondsFromGMTForDate:now];
        NSLog(@"seconds = %lu", seconds);
        
        //2.时间格式化
        //xxxx年xx月xx日   xx小时xx分钟xx秒
        //xxxx/xx/xx    xx/xx/xx
        //2.1创建一个时间格式化对象
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        //2.2格式(大MM小dd)
        formatter.dateFormat = @"YYYY年MM月dd日 z hh时mm分钟ss秒  ";
        NSString *res =[formatter stringFromDate:now];
        NSLog(@"res = %@", res);
        //2.3字符串转NSDate
        NSString *str = @"2019-04-28 GMT+8 19:25:00";
        NSDateFormatter *f2 = [NSDateFormatter new];
        f2.dateFormat = @"yyyy-MM-dd z hh:mm:ss";
        NSDate *date2 = [f2 dateFromString:str];
        //默认时间格式
        NSLog(@"date2 = %@", date2);
        //修改时间格式
        NSString *res2 = [f2 stringFromDate:date2];
        NSLog(@"res2 = %@", res2);

3.日期时间对象

NSCalendar *calendar = [NSCalendar currentCalendar];
- (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)date;
    NSDate *date = [NSDate date];
    // 1.创建日历对象
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 2.利用日历对象获取年月日时分秒
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *cmps =[calendar components:type fromDate:date];
        NSLog(@"cmps = %@", cmps);
    NSLog(@"date = %@", date);
- (NSDateComponents *)components:(NSCalendarUnit)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSCalendarOptions)opts;
    // 1.确定时间
    NSString *time1 = @"2015-06-23 12:18:15";
    NSString *time2 = @"2015-06-28 10:10:10";
    // 2.将时间转换为date
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *date1 = [formatter dateFromString:time1];
    NSDate *date2 = [formatter dateFromString:time2];
    // 3.创建日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 4.利用日历对象比较两个时间的差值
    NSDateComponents *cmps = [calendar components:type fromDate:date1 toDate:date2 options:0];
    // 5.输出结果
    NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分钟%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);

NSFileManager

        NSFileManager *fm1 = [NSFileManager defaultManager];
        NSFileManager *fm2 = [NSFileManager defaultManager];
        NSLog(@"%p   %p", &fm1, &fm2);
        //1.判断一个文件夹是否存在
        BOOL flag = [fm1 fileExistsAtPath:@"/Users/gaoxiong/Desktop/gx.plist"];
        NSLog(@"flag = %i", flag);
        //2.判断一个文件是否存在,并判断是否是文件夹
        BOOL dir = NO;
        BOOL flag1 = [fm1 fileExistsAtPath:@"/Users/gaoxiong/Desktop/gx.plist" isDirectory:&dir];
        NSLog(@"flag1 = %i, dir = %i", flag1, dir);
        //2.1是否可读
        [fm1 isReadableFileAtPath:@"/Users/gaoxiong/Desktop/gx.plist"];
        //2.2是否可写
        [fm1 isWritableFileAtPath:@"/Users/gaoxiong/Desktop/gx.plist"];
        //2.2是否可删
        [fm1 isDeletableFileAtPath:@"/Users/gaoxiong/Desktop/gx.plist"];
    
        //3.获取文件或者文件夹的属性
        NSFileManager *manager = [NSFileManager defaultManager];
        NSDictionary *info = [manager attributesOfItemAtPath:@"/Users/gaoxiong/Desktop/gx.plist" error:nil];
        NSLog(@"info = %@", info);
        //4.获取文件夹中的所有文件contentsOfDirectoryAtPath, 无法获取子文件
        NSArray *res = [manager contentsOfDirectoryAtPath:@"/Users/gaoxiong/Desktop" error:nil];
        NSLog(@"res = %@",res);
        //4.1获取文件夹中的所有文件,包括子文件subpathsOfDirectoryAtPath
        NSArray *rslt = [manager subpathsOfDirectoryAtPath:@"/Users/gaoxiong/Desktop" error:nil];
        NSLog(@"rslt = %@", rslt);
        //5.创建文件夹
        //withIntermediateDirectories,如果指定路径中有文件夹不存在,是否自动创建文件夹
        //attributes,指定创建出来的文件夹属性
        //createDirectoryAtPath 只能创建文件夹
        [manager createDirectoryAtPath:@"/Users/gaoxiong/Desktop/lu/lu" withIntermediateDirectories:YES attributes:nil error:nil];
        //6.创建文件
        //NSData : 二进制
        //createFileAtPath 只能创建文件
        NSString *str = @"lulu is pangding";
        NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
        [manager createFileAtPath:@"/Users/gaoxiong/Desktop/lu.txt" contents:data attributes:nil];
        //7.拷贝
        [manager copyItemAtPath:@"/Users/gaoxiong/Desktop/gx.plist" toPath:@"/Users/gaoxiong/Desktop/gx/gx.plist" error:nil];
        //8.移动/剪切
        [manager moveItemAtPath:@"/Users/gaoxiong/Desktop/gx.plist" toPath:@"/Users/gaoxiong/Desktop/lu/gx.plist" error:nil];
        //9.删除
        [manager removeItemAtPath:@"/Users/gaoxiong/Desktop/lu.txt" error:nil];
上一篇下一篇

猜你喜欢

热点阅读