开发笔记(字符串、数组、字典)
1.字符串(NSString)
1.1字符串的初始化及长度
1. 创建字符创
NSString *strS = @"This is a String!";
2.创建空字符串,给予赋值
NSString *strK = [[NSString alloc] init];
strK = @"This is a String!";
NSLog(@"strS:%@, strK%@",strS,strK);
3.使用变量初始化字符串
NSString *name = @"aofe";
NSString *strN = [NSString stringWithFormat:@"My name is %@",name];
NSLog(@"strN:%@",strN);
//可变类型
NSMutableString *mString1 = [NSMutableString stringWithFormat:@"%@", @"乾坤"];
4.字符串长度
NSString * lengthStr = @"hello,world";
NSLog(@"lengthStr.length = %ld",lengthStr.length);
5.子字符串所在位置及长度
NSString * mainString = @"hello,world";
NSString * subStr = @"world";
NSRange range = [mainString rangeOfString:subStr];
NSLog(@"range.location = %ld,range,length = %ld",range.location,range.length);
1.2判断是否包含某字符串的几种类型
NSString *str1 = @"NSStringInformation.txt";
1.检查字符串是否以另一个字符串开头
[str1 hasPrefix:@"NSString"] == 1? NSLog(@"YES") :NSLog(@"NO");
2.检查字符串是否以另一个字符串结尾
[str1 hasSuffix:@".txt"] == 1? NSLog(@"YES") :NSLog(@"NO");
3.检查字符串是否包含其他字符串方法1
[str1 rangeOfString:@"Information"].length > 0 ? NSLog(@"YES") :NSLog(@"NO");
4.检查字符串是否包含其他字符串方法2
if ([str1 rangeOfString:@"Infor"].location == NSNotFound) {
NSLog(@"string 不存在 Infor");
} else {
NSLog(@"string 包含 Infor");
}
5.检查字符串是否包含其他字符串方法3
if ([women containsString:@"Infor"]) {
NSLog(@"women 包含 Infor");
} else {
NSLog(@"women 不存在 Infor");
}
1.3读写字符串
// 文件路径
NSString *path = @"wenJianQuanLuJing";
1.从文件读取字符串
NSString *strW = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL];
2.将字符串写入到文件
[strW writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
1.4比较两个字符串
NSString *str1 = @"this is String1";
NSString *str2 = @"THIS is String2";
1.比较两个字符串是否相等(isEqualToString)
BOOL result1 = [str1 isEqualToString:str2];
2.compare方法(comparer返回的三种值)
2.1NSOrderedSame 判断两者内容是否相同:BOOL result = [str1 compare:str2] == NSOrderedSame;
2.2NSOrderedAscending 判断两对象值的大小(按字母顺序进行比较,str2大于str1为真):BOOL result = [str1 compare:str2] == NSOrderedAscending;
2.3NSOrderedDescending 判断两对象值的大小(按字母顺序进行比较,str2小于str1为真):BOOL result = [str1 compare:str2] == NSOrderedDescending;
3.不考虑大小写比较字符串
3.1NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,str2小于str1为真:BOOL result = [str1 caseInsensitiveCompare:str2] == NSOrderedSame;
3.2NSCaseInsensitiveSearch:不区分大小写比较 NSLiteralSearch:进行完全比较,区分大小写NSNumericSearch:比较字符串的
字符个数,而不是字符值:BOOL result = [str1 compare:str2 options:NSCaseInsensitiveSearch | NSNumericSearch] == NSOrderedSame;
1.5改变字符串的大小写
NSString *str1 = @"this is string1";
NSString *str2 = @"THIS IS STRING2";
1.全部大写
[str1 uppercaseString];
2.全部小写
[str2 lowercaseString];
3.首字母大写
[str1 capitalizedString];
1.6在字符串中搜索子串
NSString *str1 = @"This is String1";
NSString *str2 = @"is";
NSRange range = [str1 rangeOfString:str2];
NSLog(@"location:%lu,length:%lu",(unsigned long)range.location,(unsigned long)
range.length);
1.7替换字符串
NSString *strL = @"hello china";
NSString *strN = [strL stringByReplacingOccurrencesOfString:@"china" withString:@"beijing"];
NSLog(@"strL:%@,strN:%@",strL,strN);
1.8分隔字符串成数组
NSString *str = @"a b c d e";
// 以空格分隔字符串成数组
NSArray *arr = [str componentsSeparatedByString:@" "];
NSLog(@"arr:%@,arr.count:%lu",arr,(unsigned long)arr.count);
1.9数组拼接成字符串
NSArray *array = [NSArray arrayWithObjects:@"this",@"is",@"String", nil];
// 用空格隔开数组中的元素
NSString *str = [array componentsJoinedByString:@" "];
NSLog(@"str:%@",str);
2.0从字符串中抽取出新的字符串(字符串截取)
NSString *str = @"This is String";
1.从字符串的开头一直截取到指定位置,但不包括该位置的字符.
NSString *str1 = [str substringToIndex:5];// 0-5的子字符串
2.从指定位置开始(包括自定位置的字符串)一直到最后
NSString *str2 = [str substringFromIndex:5];// 5-末尾的子字符串
3.按照所给定的位置和长度,任意的从字符串中截取新的字符串
NSString *str3 = [str substringWithRange:NSMakeRange(2, 3)];// 2开始的3个字符长度的字符串
NSLog(@"str1:%@,str2:%@,str3:%@",str1,str2,str3);
4.备注(注意区分):
// 获取指定索引位置的字符:索引技术从零开始计数
NSString *charStr = @"hello,world";
char c = [charStr characterAtIndex:2];
unichar c = [charStr characterAtIndex:0];
NSLog(@"%c", c);
2.1字符串的分割
NSString * sepStr = @"hello-world";
NSArray * setArray = [sepStr componentsSeparatedByString:@"-"];
NSLog(@"setArray = %@",setArray);
NSCharacterSet * charSet = [NSCharacterSet characterSetWithCharactersInString:@"-o"];
NSArray * array = [sepStr componentsSeparatedByCharactersInSet:charSet];
NSLog(@"array = %@",array);
2.2可变字符串的操作
1.给字符串分配容量
NSMutableString *strM = [NSMutableString stringWithCapacity:100];
NSLog(@"strM:%@",strM);
2.在已有的字符串后面添加字符串
NSMutableString *strM1 = [[NSMutableString alloc] initWithString:@"This is a"];
NSLog(@"strM1:%@",strM1);
[strM1 appendString:@"NSMutableString"];
NSLog(@"strM1:%@",strM1);
3.在已有字符串中按照所给出的范围和长度删除字符
[strM1 deleteCharactersInRange:NSMakeRange(0, 5)];
NSLog(@"strM1:%@",strM1);
4.在字符串指定位置插入字符串
[strM1 insertString:@"Hello" atIndex:0];
NSLog(@"strM1:%@",strM1);
5.将已有字符串替换成其他字符串(覆盖字符串)
[strM1 setString:@"Hello World"];
NSLog(@"strM1:%@",strM1);
6.替换指定位置字符
[strM1 replaceCharactersInRange:NSMakeRange(0, 5) withString:@"Hi"];
NSLog(@"strM1:%@",strM1);
2.3追加字符串(字符串拼接)
1.追加字符串
NSString * str = @"Hello";
NSString * book = @",book";
NSString * strBook = [str stringByAppendingString:book];
NSLog(@"str = %@",str);
NSLog(@"strBook = %@",strBook);
2.追加带变量的字符串
NSString * fStr = @"Hello";
NSString * formatStr = [fStr stringByAppendingFormat:@",%@Book",@"Good"];
NSLog(@"fStr = %@",fStr);
NSLog(@"formatStr = %@",formatStr);
2.4其他使用方法
- int类型与字符串(及16进制字符串)互转
1.普通字符串与int类型互转
-(void)stringToInt{
//数字转字符串
int num = 12;
NSString * intString = [NSString stringWithFormat:@"%d",num];
NSLog(@"intString = %@",intString);
//字符串转数字
NSString * string = @"12";//会转为12;类似@”我“这样的非数字的字符串会转为0
NSInteger stringInt = [string integerValue];
NSLog(@"stringInt = %ld",stringInt);
}
2.将int类型 转为16进制的字符串1
-(void)hexStringFromNum{
int num = 16;
NSString *hexString = [NSString stringWithFormat:@"%@",[[NSString alloc] initWithFormat:@"%1x",num]];
NSLog(@"hexString = %@",hexString);
}
2.将int类型 转为16进制的字符串2(待验证)
-(void)longlongToHexStr{
NSInteger value = 16;
int len = 2;
char ASSICCHAR[] = "0123456789ABCDEF";;
char resultBuffer[len];
for (int i = 0; i < len; i++) {
resultBuffer[len - i - 1] = ASSICCHAR[(value >> (i * 4)) & 0x0F];
}
NSString * hexString = [NSString stringWithCString:resultBuffer encoding:NSASCIIStringEncoding];
NSLog(@"hexString = %@",hexString);
}
- 字符串与data互转
// 字符串与data互转
-(void)stringToData{
//把字符串再转变为二进制流
NSString * string = @"I have a dream";
NSData * data=[NSMutableData dataWithData:[string dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"data = %@",data);
//二进制流转变为字符串
NSString * dataStr=[[NSMutableString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"dataStr = %@",dataStr);
}
- Unicode数值数组、c风格字符串及oc字符串 互相转化
* 在C语言中,使用ASCII编码的字符作为字符串,并且C语言中,并没有专门管理字符串的基本数据类型
* 在OC中,只要符号符合Unicode编码,都可以作为字符串使用,在OC中,使用NSString来管理字符串
-(void)initStringFun {
1.使用Unicode数值数组转化成字符串
unichar data[6] = {97,98,99,100,101,102};
NSString * string = [[NSString alloc] initWithCharacters:data length:6];
NSLog(@"string = %@",string);
NSString * str = [NSString stringWithCharacters:data length:6];
NSLog(@"str = %@",str);
2.将c风格字符串转NSString对象
char * cStr = "hello,iOS";
NSString * cString = [[NSString alloc] initWithUTF8String:cStr];
NSLog(@"cString = %@",cString);
3.将oc字符串转为c字符串
const char * strToC = [cString UTF8String];
NSLog(@"strToC = %s",strToC);
}
- 去掉非数字字符
// 去掉非数字字符
-(void)removeUnnumberChar{
NSString * number = @"156-8888-8888";
//invertedset:为翻转
NSCharacterSet *setToRemove = [[ NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet];
NSArray * numArray = [number componentsSeparatedByCharactersInSet:setToRemove];
NSLog(@"numArray = %@",numArray);
NSString *phoneStr = [numArray componentsJoinedByString:@""];
}
- json格式字符串与字典类型互转
// 字典转为json格式字符串
-(NSString*)jsonStringFromDict {
NSDictionary * dict = @{@"1":@"test1",
@"2":@"test3"};
NSData * mData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString * dictString = [[NSString alloc] initWithData:mData encoding:NSUTF8StringEncoding];
NSLog(@"dictString = %@",dictString);
return dictString;
}
// 将json格式字符串转为字典
-(NSDictionary *)parseJSONStringToNSDictionary {
NSString * JSONString = [self jsonStringFromDict];
//将字符串转成二进制数据
NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
//利用系统自带的JSON解析,解析成字典格式
NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
//将字典返回
NSLog(@"responseJSON = %@",responseJSON);
return responseJSON;
}
2.数组(NSArray)
1.固定数组的初始化及基本使用
1.数组初始化
//创建空数组
NSArray *arr = [[NSArray alloc]init];
//对象方法创建数组 以nil结束
NSArray *arr1= [NSArray alloc]initWithObjects:@"sun",@"is",@"girl", nil];
//用已有数组创建新数组
NSArray *arr2 = [[NSArray array]initWithArray:arr];
//通过类方法创建数组
NSArray *arr3 = [NSArray arrayWithArray:arr2];
//类方法创建空数组
NSArray *arr4 = [NSArray array];
2.基本方法
取一个元素:
NSArray *arr = @[@"sun",@"is",@"a",@"smilling",@"girl"];
NSString *string = [arr objectAtIndex:2];
//取第一个元素
NSString *first = [arr firstObject];
//取最后一个元素
NSString *last = [arr lastObject];
//简单方法取一个元素
NSString *str2 = arr[3];
取多个元素:
//NSIndexSet:是一个索引集合,原理上与数组类似,只不过这是一个无序的
NSIndexSet *set4 = [[NSIndexSet alloc]initWithIndexesInRange:NSMakeRange(1, 2)];
NSArray *arr3 = [array1 objectAtIndex:set4];
简单方法截取多个元素
NSArray *arr4 = [array1 subarrayWithRange:NSMakeRange(2, 3)];
//for in 快速遍历 只针对数组来说,in的前面是数组中的元素, in后面是要遍历的集合(数组/字典)
for (NSString *str in array1) {
NSLog(@"%@",str);
}
2.可变数组的初始化及基本使用
1.数据初始化
//创建空数组
NSMutableArray *mutArray = [NSMutableArray array];
//capacity
NSMutableArray *mutAr = [NSMutableArray arrayWithCapacity:100];
NSMutableArray *mutcap = [[NSMutableArray alloc]initWithCapacity:100];
NSArray *array = @[@"dskfj",@"df",@"sd",@"f"];
NSMutableArray *mutarr3 = [[NSMutableArray alloc]initWithArray:array];
//通过类方法
NSMutableArray *mutarr5 = [NSMutableArray arrayWithObjects:@"sdj",@"dsf", nil];
2.基本方法
增加元素
NSMutableArray *mutArray1 = [NSMutableArray arrayWithObjects:@"sunck", @"is", @"a", @"nice", @"man", nil];
//1.增加到数组的结尾
//1.增加一个元素
[mutArray1 addObject:@"!"];
NSLog(@"mutArray1-1 = %@", mutArray1);
//2.增加多个
[mutArray1 addObjectsFromArray:@[@"Oh", @"right"]];
NSLog(@"mutArray1-2 = %@", mutArray1);
//2.在数组中增加(未整理)
删除元素
//注意:如果数组中有多个相同的元素,那么会全部删除
//1.删除一个元素
//1.1按元素删除 注意:如果数组中有多个相同的元素,那么会全部删除
NSMutableArray *mutArray = [NSMutableArray arrayWithObjects:@"sd",@"sun",@"id",@"good",@"girl", nil];
[mutArray removeObject:@"sd"];
//1.2按下标删除
[mutArray removeObjectAtIndex:3];
//1.3删除最后一个
[mutArray removeLastObject];
//2.删除多个
//在range范围内删除第一个参数的中的数据
NSIndexSet *set4 = [[NSIndexSet alloc]initWithIndexesInRange:NSMakeRange(5, 2)];
[mutArray removeObjectsAtIndexes:set4];
//3.删除全部
[mutArray removeAllObjects];
3.数组的排序(介绍常用的几种,其他方法不介绍)
NSComparisonResult为枚举类型,其中:
NSOrderedAscending:左边的操作对象小于右边的对象(升序)
NSOrderedSame:左右两边对象相等(相等)
NSOrderedDescending:左边的操作对象大于右边的对象(降序)
-
直接对数组进行排序:
方法1:利用数组的sortedArrayUsingComparator调用NSComparator
// 升序
NSArray *tMlist = @[@1,@5,@2,@6,@3,@7,@9];
NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *tNumber1 = (NSNumber *)obj1;
NSNumber *tNumber2 = (NSNumber *)obj2;
// 因为满足sortedArrayUsingComparator方法的默认排序顺序,则不需要交换
if ([tNumber1 integerValue] < [tNumber2 integerValue]) return NSOrderedAscending;
return NSOrderedDescending;
}];
NSLog(@"升序%@",tArray.description);
// 降序
NSArray *tMlist = @[@1,@5,@2,@6,@3,@7,@9];
NSArray *tArray = [tMlist sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSNumber *tNumber1 = (NSNumber *)obj1;
NSNumber *tNumber2 = (NSNumber *)obj2;
// 因为不满足sortedArrayUsingComparator方法的默认排序顺序,则需要交换
if ([tNumber1 integerValue] < [tNumber2 integerValue]) return NSOrderedDescending;
return NSOrderedAscending;
}];
NSLog(@"降序%@",tArray.description);
方法2:sortedArrayUsingSelector
NSMutableArray *array = [NSMutableArray arrayWithObjects:
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj0", [NSNumber numberWithInt:0], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj5", [NSNumber numberWithInt:5], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj2", [NSNumber numberWithInt:2], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj3", [NSNumber numberWithInt:3], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj1", [NSNumber numberWithInt:1], nil],
[NSDictionary dictionaryWithObjectsAndKeys:@"Obj4", [NSNumber numberWithInt:4], nil], nil];
NSArray *resultArray = [array sortedArrayUsingSelector:@selector(compare:)];
//因为NSDictionary没有compare的排序比较方法,所以需要我们自己写一个
- (NSComparisonResult)compare: (NSDictionary *)otherDictionary {
NSDictionary *tempDictionary = (NSDictionary *)self;
NSNumber *number1 = [[tempDictionary allKeys] objectAtIndex:0];
NSNumber *number2 = [[otherDictionary allKeys] objectAtIndex:0];
NSComparisonResult result = [number1 compare:number2];
return result == NSOrderedAscending;// 升序
// return result ==NSOrderedDescending;// 降序
}
-
根据数组中的某个或多个关键词进行排序:
方法1:使用NSDescriptor排序
1.单关键字排序
NSMutableArray *array = [NSMutableArray array];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"key" ascending:YES];
[array sortUsingDescriptors:[NSArray arrayWithObject:sort]];
2.多关键字排序
NSMutableArray *array = [NSMutableArray array];
......
NSSortDescriptor *sort1 = [NSSortDescriptor sortDescriptorWithKey:@"key1" ascending:YES];
NSSortDescriptor *sort2 = [NSSortDescriptor sortDescriptorWithKey:@"key2" ascending:NO];
[array sortUsingDescriptors:[NSArray arrayWithObjects:sort1, sort2, nil]];
其中ascending为YES表示升序排列
key : 排序key, 某个对象的属性名称; 如果对字符串进行排序, 则传nil
ascending : 是否升序, YES-升序, NO-降序
- (void)demoSortDescription
{
NSDictionary *dic1 = [NSDictionary dictionaryWithObjectsAndKeys:@"2030",@"year", @"1",@"month",nil];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"2010",@"year", @"2",@"month", nil];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjectsAndKeys:@"2050",@"year", @"3",@"month" ,nil];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjectsAndKeys:@"2014",@"year", @"4",@"month",nil];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjectsAndKeys:@"2050",@"year", @"4",@"month",nil];
NSMutableArray *arrM = [NSMutableArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, nil];
NSSortDescriptor *descripor = [NSSortDescriptor sortDescriptorWithKey:@"year" ascending:YES];
NSSortDescriptor *descripor2 = [NSSortDescriptor sortDescriptorWithKey:@"month" ascending:YES];
[arrM sortUsingDescriptors:[NSArray arrayWithObjects:descripor, descripor2, nil]];//先按第一个来拍,再按第二个来拍
NSLog(@"resultArr = %@", arrM);
}
相关链接:https://www.jianshu.com/p/2e09f9d30a40
方法2:使用NSComparisonResult排序
NSComparator cmptr = ^(FPTitleLayer *obj1, FPTitleLayer *obj2) {// 关键字showTimeStr
if ([obj1.showTimeStr integerValue] > [obj2.showTimeStr integerValue]) {
return (NSComparisonResult)NSOrderedDescending;// 降序
} else if ([obj1.showTimeStr integerValue] < [obj2.showTimeStr integerValue]) {
return (NSComparisonResult)NSOrderedAscending;// 升序
} else {
return (NSComparisonResult)NSOrderedSame;
}
};
NSArray *sorArray = [listArray sortedArrayUsingComparator:cmptr];
4.数组的去重
1.通过valueForKeyPath, 去重只需一行代码
NSArray *originalArr = @[@1, @2, @3, @1, @3];
NSArray *result = [originalArr valueForKeyPath:@"@distinctUnionOfObjects.self"];
2.利用NSSet特性, 放入集合自动去重
NSSet的特性: 确定性、无序性、互异性;这种方法更快,利用NSSet不会添加重复元素的特性。不过去重的数组
没有进行排序,如果需要排序,可以使用NSSortDescriptor类
NSArray *originalArr = @[@1, @2, @3, @1, @3];
NSSet *set = [NSSet setWithArray:originalArr];
NSLog(@"result: %@", [set allObjects]);
3.利用NSDictionary的AllKeys(AllValues)方法
可以将NSArray中的元素存入一个字典,然后利用AllKeys或者AllValues取得字典的所有键或值,这些键或值都是去重的
NSArray *originalArr = @[@1, @2, @3, @1, @3];
NSMutableDictionary *dictM = [NSMutableDictionary dictionary];
for (NSNumber *n in originalArr) {
[dict setObject:n forKey:n];
}
NSLog(@"%@",[dictM allValues]);
4.开辟新的内存空间
判断是否存在,若不存在则添加到数组中,得到最终结果的顺序不发生变化
NSArray *originalArr = @[@1, @2, @3, @1, @3];
NSMutableArray *resultArrM = [NSMutableArray array];
for (NSString *item in originalArr) {
if (![resultArrM containsObject:item]) {
[resultArrM addObject:item];
}
}
NSLog(@"result : %@", resultArrM);
- 相关链接(开发笔记三-17):https://www.jianshu.com/p/af363061c437
5.数组的遍历(筛选数组中想要的数据)
NSArray * array = @[@"1",@"2",@"three",@"4"];
//方法一
for (int i=0; i<[array count]; i++) {
NSLog(@"array[%d]=%@",i,array[i]);
}
//方法二(for-in)
for (NSString * str in array) {
NSLog(@"%@",str);
}
https://blog.csdn.net/cloud_pro/article/details/50998530
6.数组的转换(自己互换+转换其他如字典..)
自己互换
1.不可变数组转成可变数组
NSArray * array = @[@"one",@"two"];
NSMutableArray * muArr = [[NSMutableArray alloc] initWithArray:array]; // [array mutableCopy];
2.可变数组转成不可变数组
[muArr copy]
数组与字符串的互转
1.字符串-->数组
NSString * str = @"I am in shanghai";
NSArray * strArr = [str componentsSeparatedByString:@" "];
2.数组-->字符串
NSString * str1 = [strArr componentsJoinedByString:@"-"];
//将数组中的元素按照给定的字符串格式拼接成一个完整的字符串对象
- (NSString *)componentsJoinedByString:(NSString *)separator;
//例:有一个数组,通过&将所有元素拼接成一个字符串
NSArray *array = @[@"北京", @"大连", @"河南", @"上海", @"广州", @"西安"];
NSString *string = [array componentsJoinedByString:@"&"];
NSLog(@"%@", string);
输出结果:北京&大连&河南&上海&广州&西安
数组与字典互转
NSMutableArray *dicToArray = [NSMutableArray array];NSMutableDictionary *arrayToDic = [NSMutableDictionary dictionary];
NSDictionary *dic = @{@"1":@"one",@"2":@"two",@"3":@"three"};
//字典转数组
[dic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
[dicToArray addObject:[NSString stringWithFormat:@"%@:%@",key,obj]];
}];
NSLog(@"dicToArray====%@",dicToArray);
//数组转字典
[dicToArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSLog(@"obj===%@===idx===%lu",obj,(unsigned long)idx);
NSArray *array = [obj componentsSeparatedByString:@":"];//分割字符串
[arrayToDic setObject:array[1] forKey:array[0]];
}];
NSLog(@"arrayToDic====%@",arrayToDic);
dicToArray====(
"1:one",
"2:two",
"3:three"
)
arrayToDic===={
1 = one;
2 = two;
3 = three;
}
7.取出一组数据相同元素
8.其他使用方法
1.数组中元素个数
NSArray array = @[@"1",@"2",@"3"];
NSUInteger count = [array count];// 一般个数就是array.count
NSLog(@"%lu",count);
2.获取固定数组中的元素
NSArray array = @[@"1",@"2",@"3"];
Person *p = [array objectAtIndex:0];// 普通获取元素方法
Person *p = array[0]; // 快速获取方法
3.判断数组中是否包含指定的元素,获取该元素在数组中的下标
NSArray * arr = @[@"1",@"2",@"3",@"4",@"5"];
if([arr containsObject:@"3"]) { // 是否包含元素@“3”
NSInteger index = [arr indexOfObject:@"3"];// 获取下标
NSLog(@"%ld",index);// 输出是2
NSLog(@"包含");
} else {
NSLog(@"不包含");
}
4.基本类型转换成数组对象
// 数组中可以存储不同类型的对象
int i = 10;
float f = 3.14;
NSNumber * number = [NSNumber numberWithInt:i];
NSNumber * number1 = [NSNumber numberWithFloat:f];
NSArray * array = @[@"one",@"10",number,number1]; // array == (one,10,10,"3.14");
// 数组中存储的是对象的地址,数组中也可以存储数组的地址
NSArray * array1 = @[@"1",@"2",@"3"];
NSArray * array2 = @[array,array1];
3.字典(NSDictionary)
1.固定字典的初始化及基本方法
1.创建不可变字典
NSDictionary * dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"one",@"1",@"two",@"2",nil];
NSDictionary * dic1 = @{@"3":@"three",@"4":@"four"}; //快速创建字典
2.字典可以存储任意类型的对象
NSArray * array = @[@"one",@"333"];
NSNumber * num = [NSNumber numberWithInt:10];
NSDicitonary * dic2 = @{@"dic":dic,@"num":num,@"array":array};
3.获取字典的长度(键的个数)
NSUInteger count = [dic2 count];
4.从字典中取值
NSString * arr = [dic3 objectForKey:@"array"];
NSDictionary * dic4 = dic3[@"dic"];//快速取值
NSNumber * number = dic3[@"num"];
2.可变字典的初始化及基本方法
1.创建可变字典
1.1创建一个空字典,常用的方法有:
NSMutableDictionary *mdict = [@{} mutableCopy];
NSMutableDictionary *mdict = [NSMutableDictionary dictionary];
1.2创建带值的字典
NSMutableDictionary * muDic = [[NAMutableDictionary alloc] initWithObjectsAndKeys:@"one",@"1",nil];
1.3创建字典的的时候就初始化它的大小(如以下分配了可以容纳10个键值对内容的内存)
NSMutableDictionary *mdict = [NSMutableDictionary dictionaryWithCapacity:10];
1.4向可变字典中添加不可变字典
NSDictionary * dic = @{@"3":@"three"};
NSMutableDictionary * muDic2 = [[NSMutableDictionary alloc] initWithDictionary:dic];
2.向字典中插入数据(因为字典是无序的,因此不用指定插入的位置。如果字典中已经存在对应的KEY值,
那么就直接替换掉该KEY对应的值,也就是相当于修改操作;如果不存在,则将该“键值对”添加到字典当中)
[muDic2 setObject:@"two" forKey:@"2"];
3.删除数据(这是指定“键”的方式删除字典中对应的“键值对”,如果该Key不存在,则不做任何操作)
[muDic2 removeObjectForKey:@"2"];
4.全部删除
[muDic removeAllObjects];
3.遍历字典
// 方法1
NSDictionary *dict = @{@"1":@"11", @"2":@"22", @"3":@"33"};
NSArray *keysArray = [dict allKeys];
for (int i = 0; i < keysArray.count; i++) {// 根据键值处理字典中的每一项
NSString *key = keysArray[i];
NSString *value = [dict valueForKey:key];
NSLog(@"%@ = %@",key,value);// 得到字典所有的键值对
}
NSLog(@"%zd",dic.count);
// 方法2 快速遍历
for (NSString *key in dict) {//处理字典的键值
NSString *value = dict[key];
NSLog(@"%@", value);
}
反向遍历可以使用:for (NSString *obj in [iosArray reverseObjectEnumerator])
4.字典的转换
字典-->数组
NSDictionary *dic = @{@"1":@"two",@"2":@"kk"};
NSArray *keysArr = [dic allKeys];
NSArray *valuaesArr = [dic allValues];
5.其他使用方法
1.根据某个key找到对应的value值
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"val1", @"key1",
@"val2", @"key2", nil];
NSObject *value = [dict objectForKey:@"key1"];
if (value != nil) {
NSLog(@"value in dict: %@", value);
}
运行结果如下:2016-07-24 10:20:09.012 OCTest[2736:103393] value in dict: val1
2.根据某个value找到对应的key值
NSString *objectEightId;
NSDictionary *userDic = @{@"1":@"qwwr",@"2":@"qwrewr",@"3":@"已知道的value",@"4":@"adasfsgf"};
[userDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSLog(@"key = %@ and obj = %@", key, obj);
if ([obj isEqualToString: "已知道的value"]) {
objectEightId = key;
NSLog(@"----------%@",objectEightId);
}
}];
3.得到字典中所有的key
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"val1", @"key1",
@"val2", @"key2", nil];
4.遍历字典中的所有value
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"val1", @"key1",
@"val2", @"key2", nil];
- 字典的代理方法总结:https://www.jianshu.com/p/87506037a954
备注
1.以上三者之间的互相转换具体查看相关模块
2.可变是固定的子类,所以都可以用父类的方法;如NSMutableArray是NSArray的子类,可以动态的新增和删除其数组中的元素,其他的用法均与NSArray一致