练习与示例:
1.字典相关练习
//查看字典中键值对个数
NSLog(@"%lu", dic.count);
//字典的一种遍历方式
//查找字典中的所有key值并把它放到数组中
NSArray *keyArray = dic.allKeys;
//遍历数组
for (int i = 0; i < keyArray.count; i++) {
NSString *key = keyArray[i];
//通过key获取value
NSString *value = [dic objectForKey:key];
NSLog(@"key:%@, value:%@", key, value);
}
2.可变字典
//创建一个空字典
NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
//创建有键值对的字典
NSMutableDictionary *mutableDic1 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"徐博杰",@"name",@"99",@"age", nil];
NSMutableDictionary *mutableDic2 = [@{@"name" : @"闫磊", @"age" : @"100"} mutableCopy];
//添加
[mutableDic setObject:@"mc海杰" forKey:@"name"];
NSLog(@"%@", mutableDic);
//移除
[mutableDic removeObjectForKey:@"name"];
NSLog(@"%@", mutableDic);
//清空字典
[mutableDic1 removeAllObjects];
作业:
- 新建Contact类:
- 在.h中声明属性与方法(包括初始化方法):
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *gender;
@property (nonatomic, retain) NSString *phoneNumber;
@property (nonatomic, retain) NSString *group;
- (instancetype)initWithName:(NSString *)name gender:(NSString *)gender phoneNumber:(NSString *)phoneNumber;
- (void)show;
- 导入一个自己写的获取拼音首字母的头文件和Contact类的头文件:
#import "Contact.h"
#import "NSString+EAPinYin.h"
- 在.m中进行方法的实现:
- (instancetype)initWithName:(NSString *)name gender:(NSString *)gender phoneNumber:(NSString *)phoneNumber {
self = [super init];
if (self) {
_name = name;
_gender = gender;
_phoneNumber = phoneNumber;
_group = name.firstCharacterForPinYinString;
}
return self;
}
- (void)show {
NSLog(@"name:%@,gender:%@,phoneNumber:%@,group:%@",_name,_gender,_phoneNumber,_group);
}
- 在主函数中进行实现:
NSMutableDictionary *mutDic = [NSMutableDictionary dictionary];
for (char c = 'A'; c <= 'Z'; c++) {
NSString *key = [NSString stringWithFormat:@"%c",c];
NSMutableArray *contactArr = [NSMutableArray array];
[mutDic setObject:contactArr forKey:key];
}
Contact *contact = [[Contact alloc]initWithName:@"李四" gender:@"男" phoneNumber:@"123942321347"];
//判断姓名和电话是否为空
if (contact.name != nil && contact.name.length != 0 && contact.phoneNumber != nil && contact.phoneNumber.length != 0) {
NSMutableArray *contactArray = [mutDic objectForKey:contact.group];
[contactArray addObject:contact];
} else {
NSLog(@"姓名电话不能为空");
}
NSArray *keyArray = mutDic.allKeys;
for (int i = 0; i < keyArray.count; i++) {
NSString *key = keyArray[i];
NSMutableArray *contactArray = [mutDic objectForKey:key];
for (int j = 0; j < contactArray.count; j++) {
Contact *contact = contactArray[j];
[contact show];
}
}
}