【OC语言】第九篇·NSString,NSArry,NSDictionary

来源:互联网 发布:linux命令 mkdir 编辑:程序博客网 时间:2024/06/06 18:34
一、Foundation
    1. 框架:框架是由许多类、方法、函数、文档按照一定的逻辑组织起来的集合。
    2. 作用:
       1) Foundation框架是Mac/iOS中其它框架的基础
        2)Foundation框架中包含了许多开发中常用的数据类型
    3. 使用: #import <Foundation/Foundation.h>

二、NSString
    1. 一个NSString对象就代表一个字符串,一般称为字符串类。
    2. 格式化创建:
          NSString *str = [NSString stringWithFormat:@"%@,@"string""];
          NSString *str1 = [[NSString alloc] initWithFormat:@"My age is %d",10];
   3. 文件读写
       写:writeToFile:@"文件的路径" atomically:原子性(YES/NO) encoding:NSUTF8StringEncoding error:nil
       读:[NSString stringWithContentsOfFile:@"待读取的文件的路径" encoding:NSUTF8StringEncoding(编码) error:&err(有没有错误)]
    4. 字符串比较
      1)取出每个字符的ASCII码值 ,比较ASCII码值大小
      2)compare方法比较大小
            compare 默认的区分大小写的
            compare 这个函数,不能增加条件
      3)比较的时候,不区分大小写,参考字符的个数
    NSComparisonResult result = [str1 compare:str2 options:NSCaseInsensitiveSearch|NSNumericSearch];
    5. 比较字符串是否相等
      1)==是单纯的地址比较
      2)判断字符串内容真正是否相等使用是:isEqualToString: (注意:他是区分大小写的)
    6. 检测字符串的前缀:[str hasPrefix:@"要检测的内容"];
        检测字符串的后缀:[str hasSuffix:@"带检测的后缀"];
    7. 字符串查找:NSRange range =  [str1 rangeOfString:str2];
        range.location 表示字符串首次出现的位置
        range.length 字符串出现的长度(实质上就是子字符串的长度)
        查找2 在 1中首次出现的位置,如果查找到返回2在1中的位置和长度
        如果查找不到返回的信息:location   特别大的数(NSNotFound)最大的long类型的数    length     0
     8. 字符串截取:

NSString *str = @"http://www.baidu.com"; //1) 从xx位置开始,到最后结束,从0开始计算位置(包含xx这个位置的字符) NSString *str1 = [str substringFromIndex:5]; NSLog(@"str1 = %@",str1); //2) 从开始位置,到xx位置结束(不包含xx这个位置) NSString *str2 = [str substringToIndex:5]; NSLog(@"str2 = %@",str2); //3) 截取一个范围 range NSRange r1 = {3,4}; NSString *str3 = [str substringWithRange:r1]; NSLog(@"str3 = %@",str3);

    9.字符串替换:
        [str stringByReplacingOccurrencesOfString:@"源字符串中的内容" withString:@"要替换成新的内容"];
   10. 字符串转换为整型:[str intValue]  
         字符串转换为float型:[str floatValue]  
         字符串转换为double型:[str doubleValue]  
    11.OC的字符串和C的字符串互相转换问题

char *s = "zhangsanfeng"; printf("%s\n",s); //思路:创建一个OC的字符串对象,用C语言的字符串创建 NSString *str = [NSString stringWithUTF8String:s]; NSLog(@"str = %@",str); //2) OC对象 --> C的字符串 NSString *str2 = @"zbz"; // 把str2 转 C的字符串 const char *s1 = [str2 UTF8String]; printf("s1 = %s\n",s1);        

        
三、NSURL
    1.  URL:统一资源定位符
    2. NSURL:OC提供了一个URL处理的一个类
    3. 使用:通过 URLWithString 构建一个NSURL
    4.  URLWithString作用:
      1)可以构建本地路径的URL
      2)可以构建路径,调用手机系统的程序
    5. fileURLWithPath 获取本地文件路径
    6. 读:[NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];

//写操作 NSURL *url = [NSURL URLWithString:@"file:///Users/Mac-leaf/Desktop/str.txt"]; NSURL *url1 = [NSURL fileURLWithPath:@"/Users/Mac-leaf/Desktop/str.txt"]; //本地文件 NSError *error; NSString *str = @"This is a string,write by NSURL"; [str writeToURL:url atomically:YES encoding:NSUTF8StringEncoding error:&error]; if (error == nil) { NSLog(@"Write success"); } else{ NSLog(@"write failed!\n%@",error); } //读操作 NSString *str1; str1 = [NSString stringWithContentsOfURL:url1 encoding:NSUTF8StringEncoding error:&error]; if (error == nil) { NSLog(@"str1 = %@",str1); } else{ NSLog(@"%@",error); }



四、NSRange
    1. NSRange range;  //range 结构体变量
    2. NSRange使用

NSRange range; //range 结构体变量 NSRange *r ; // r 结构体指针 //range变量的初始化方式 //1) 通过结构体变量访问成员 range.location = 3; range.length = 2; //2) 结构体变量整体赋值 range = (NSRange){5,3}; NSRange r2 = {4,5}; //最简单的 //3) NSRange r3 = {.location = 3}; //只是给结构体变量中的.location 成员赋值 //4) OC中新增的 //NSMakeRange函数的作用给 NSRange结构体变量赋值 NSRange r4 = NSMakeRange(3, 3); //查看结构体变量的值 NSLog(@"%ld,%ld",r4.location,r4.length); //可以把结构体变量转换为 NSString类型 NSLog(@"%@",NSStringFromRange(r4));


五、NSMutableString
    1. NSString 是不可变的,里面的文字内容是不能进行修改的
    2. NSMutableString 是可变的,里面的文字内容可以随时改变(相当于字符串链表)
    3. NSMutableString 能使用NSString的所有方法
    4. 不可变:指的是字符串在内存中占用的存储空间是固定的,并且存储的内容不能发生变化
        可变:指的是字符串在内存中占用的内存空间不可不固定,并且存储的内容可以被修改

六、NSArray
    1. 特点:
      1)一旦创建成功,内容不可改变
      2)只能存放OC对象
    2. 数组创建

//1)创建一个空数组 NSArray *arr1 = [NSArray array]; //2)创建数组,只有一个元素 NSArray *arr2 = [NSArray arrayWithObject:@"1"]; //3)创建数组,有多个元素 // nil 表示数组赋值结束 // 常见写法 NSArray *arr3 = [NSArray arrayWithObjects:@"one",@"two",@1, nil]; //4)调用对象方法,创建数组 //nil Nil NULL NSNULL NSArray *arr4 = [[NSArray alloc] initWithObjects:@"three",@"four", nil]; //5)用一个数组可以创建另外一个数组 NSArray *arr5 = [NSArray arrayWithArray:arr3];

NSLog(@"arr5 = %@",arr5);

    4. NSArry不能存储nil,因为系统默认nil就是数组的结束标记。
    5. 获取数组的长度:数组.count (%ld)
    6. 根据下标获取对应的对象:[数组名 objectAtIndex:下标]
    7. 返回元素的下标:[数组名 indexOfObject:@"对象元素"]
    8. 数组中是否包含了某个元素:BOOL [数组名 containsObject:@"对象元素"]
    9. 用简化的方式,定义数组:格式  @[ 数组元素 ]
         例如:NSArray *arr = @[@"1",@"one",@"3",@4,@"ONE"];
    10. 用简化的方式访问数组元素:
          str = arr[1];   //C语言形式的数组元素访问
    11. 数组遍历

//1) 普通的方式,通过下标访问 for (int i=0; i<arr.count; i++) { NSLog(@"-> %@",arr[i]); }

//2) 快速枚举法 for循环的增强形式 for (NSString * str in arr) { NSLog(@"---> %@",str); } //3) 使用block的方式,进行访问 // 数组元素 元素下标 是否停止 [arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if(idx == 2){ *stop = YES; //停止 // break; }else{ NSLog(@"idx = %ld,obj = %@",idx,obj); } }];

    12. 把数组中的元素用 "-" 连接起来:[数组 componentsJoinedByString @"分隔符"];
         例如: NSString *str = [arr componentsJoinedByString:@"-"];
    13. 给一个字符串分割成一个数组:
         例如:NSString *str2 = @"400-800-12580";
                     NSArray *arr2 = [str2 componentsSeparatedByString:@"-"];
  
七、NSMultableArray
用法:

//1.创建数组 //1)空数组 NSMutableArray *arr1 = [NSMutableArray array]; NSLog(@"%p",arr1); //2)创建的时候初始化一个元素 NSMutableArray *arr2 = [NSMutableArray arrayWithObject:@"one"]; //3)创建数组的时候,初始化多个元素 NSMutableArray *arr3 = [NSMutableArray arrayWithObjects:@"one",@"two",@3,nil]; //4)创建一个数组,并且指定长度, NSMutableArray *arr4 = [NSMutableArray arrayWithCapacity:5]; //2. 添加元素 [arr1 addObject:@"fengjie"]; NSLog(@"%p",arr1); //插入元素到指定的位置 [arr1 insertObject:@"zbz" atIndex:0]; //3. 删除元素 //根据对象内容删除 [arr1 removeObject:@"zbz"]; //根据位置删除 [arr1 removeObjectAtIndex:1]; //全部删除 [arr1 removeAllObjects]; //4.修改元素 [arr3 replaceObjectAtIndex:1 withObject:@"four"]; //更加简单地方法 arr3[1] = @"five"; NSLog(@"%@",arr3); //5.查找元素 BOOL isSearch = [arr3 containsObject:@"four"]; NSLog(@"%d",isSearch); //6.交换元素 NSMutableArray *arr5 =[NSMutableArray arrayWithObjects:@1,@2,@3,@4,@5, nil]; // 可以交换数组元素 [arr5 exchangeObjectAtIndex:0 withObjectAtIndex:4]; NSLog(@"%@",arr5);


八、NSDictionary
    1. NSDictionary 不可变的,一旦创建内容就不能添加/删除(不能改动)
    2. NSDictionary的使用

//1)创建空字典 NSDictionary *dict1 = [NSDictionary dictionary]; //无意义不能用 //2)创建只有一组键值对的字典 NSDictionary *dict2 = [NSDictionary dictionaryWithObject:@"zhangsan" forKey:@"zs"]; //3)创建多组键值对的字典 NSDictionary *dict3 = [NSDictionary dictionaryWithObjectsAndKeys:@"value1",@"k1",@"value2",@"k2", nil]; //注意:字典的key值和value值,都必须是对象 //4)快速创建一个字典 //@{,,key值:value值,,,}; //key值不能重复:如果重复了,也不会报错;如果重复了,最后添加的将不能够保存到字典中 NSDictionary *dict4 = @{@"zs":@"zhaosi",@"zs":@"zhangsan",@"ls":@"lisi",@"bz":@"banzhang"}; NSLog(@"%@",dict4); //以%@格式打印字典,控制台输出一个{ }

//5)获取字典的长度 NSLog(@"%lu",dict4.count); //6)根据key值取出value值 NSString *str = [dict4 objectForKey:@"zs"]; NSLog(@"str = %@",str); //7)字典的遍历问题 //第一步:获取所有的key //第二步:根据key获取value for(NSString *key in dict4){ NSLog(@"key = %@,value = %@",key,[dict4 objectForKey:key]); } [dict4 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { NSLog(@"%@ --> %@",key,obj); }];

  
 3. NSDictionary的文件操作

//1)用简写形式定义一个字典 NSDictionary *dict = @{@"zbz":@"zhangbozhi",@"cgx":@"chenguanxi",@"xzmly":@"hello"}; //2)用简写形式,获取key对应的value NSLog(@"%@",dict[@"zbz"]); //3)把字典保存到文件中 BOOL isWrite = [dict writeToFile:@"/Users/Mac-leaf/Desktop/dict.plist" atomically:YES]; if (isWrite) { NSLog(@"写入成功"); } //4)从文件中读取字典 NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/Mac-leaf/Desktop/dict.plist"]; NSLog(@"readDict = %@",readDict);


九、NSMultableDictionary
使用:

//1)可变字典的创建 NSMutableDictionary *dict1 = [NSMutableDictionary dictionary]; //创建空字典 NSMutableDictionary *dict2 = [NSMutableDictionary dictionaryWithCapacity:3]; //2)给可变字典添加键值对 [dict1 setValue:@"zhaosi" forKey:@"ls"];//因为key值重复了,所以添加不上 [dict1 setValue:@"lisi" forKey:@"ls"]; // ls [dict1 setValue:@"liuneng" forKey:@"ln"]; NSLog(@"%@",dict1); //3)删除 [dict1 removeObjectForKey:@"ls"]; [dict1 removeAllObjects]; NSLog(@"%@",dict1);

//4)修改 [dict1 setObject:@"zhaosi" forKey:@"ls"]; //简写形式 dict1[@"ls"] = @"xxxxx"; NSLog(@"%@",dict1);

//5)查找 //获取所有的key值 NSArray *arr = [dict1 allKeys]; if([arr containsObject:@"ls"]){ NSLog(@"存在ls的key"); }

0 0
原创粉丝点击