練習(xí)與示例:
1.字典相關(guān)練習(xí)
//查看字典中鍵值對(duì)個(gè)數(shù)
NSLog(@"%lu", dic.count);
//字典的一種遍歷方式
//查找字典中的所有key值并把它放到數(shù)組中
NSArray *keyArray = dic.allKeys;
//遍歷數(shù)組
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.可變字典
//創(chuàng)建一個(gè)空字典
NSMutableDictionary *mutableDic = [NSMutableDictionary dictionary];
//創(chuàng)建有鍵值對(duì)的字典
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];
作業(yè):
- 新建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;
- 導(dǎo)入一個(gè)自己寫的獲取拼音首字母的頭文件和Contact類的頭文件:
#import "Contact.h"
#import "NSString+EAPinYin.h"
- 在.m中進(jìn)行方法的實(shí)現(xiàn):
- (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);
}
- 在主函數(shù)中進(jìn)行實(shí)現(xiàn):
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];
}
}
}