知识点:
定义:字典(dictionary)是关键字及其定义的集合。
上代码:
/*
* NSDictionary 不可变字典
*
*/
// 1、创建字典对象的常用方法
//在床架你字典对象时需要赋值键值对,但是顺序为:值,键(值在前,键在后的形式)。
NSDictionary *dic1 = [[NSDictionary alloc] initWithObjectsAndKeys:@"wang", @"name", @33, @"age", @"man", @"gender", nil] ;
NSLog( @"%@", dic1 ) ;
NSDictionary *dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"zhen", @"name", @22, @"age", @"nv", @"gender", nil] ;
NSLog( @"%@", dic2 ) ;
NSArray *keys = @[@"name", @"age", @"gender"] ;
NSArray *values = @[@"wang", @33, @"male"] ;
//创建字典对象时两个数组元素个数必须一致
NSDictionary *dic3 = [[NSDictionary alloc] initWithObjects:values forKeys:keys] ;
NSLog( @"%@", dic3 ) ;
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:values forKeys:keys] ;
NSLog( @"%@", dic4 ) ;
//通过count方法获取字典中键值对的个数
NSLog( @"%ld", [dic4 count] ) ;
//获取字典中所有的键
NSArray *allKeys = [dic4 allKeys] ;
NSLog( @"%@", allKeys ) ;
//获取字典中所有的值
NSArray *allValues = [dic4 allValues] ;
NSLog( @"%@", allValues ) ;
//通过指定的键获取其在字典中对应的值
id object = [dic4 objectForKey:@"age"] ;
NSLog( @"%@", object ) ;
for (int i = 0 ; i < [dic4 count]; i++ ) {
id key = [allKeys objectAtIndex:i] ;
id value = [dic4 objectForKey:key] ;
NSLog( @"%@", value ) ;
//[NSString class]返回 NSString 类型的对象
//isKindOfClass判断value是否是NSString 类型的对象
NSString *result = [value isKindOfClass:[NSString class]] ? @"YES" : @"NO" ;
NSLog( @"%@:%@-->%@", key, value, result ) ;
}
//字典的语法糖形式(注意 ‘:’和‘,’是成对出现的)
NSDictionary *dic5 = @{@"name": @"wang", @"age": @33, @"gender": @"man"} ;
NSLog( @"%@", dic5 ) ;
/*
* NSMutableDictionary 可变 字典
*
*/
//initWithDictionary 和 dictionaryWithDictionary 能将不可变字典变成可变字典
NSMutableDictionary *dic6 = [[NSMutableDictionary alloc] initWithDictionary:dic5] ;
NSLog( @"%@", dic6 ) ;
NSMutableDictionary *dic7 = [NSMutableDictionary dictionaryWithDictionary:dic5] ;
NSLog( @"%@", dic7 ) ;
//两种初始化方式
NSMutableDictionary *dic8 = [[NSMutableDictionary alloc] init] ;
NSLog( @"%@", dic8 ) ;
NSMutableDictionary *dic9 = [NSMutableDictionary dictionary] ;
NSLog( @"%@", dic9 ) ;
//增加 键值对
[dic9 setObject:@"wang" forKey:@"name"] ;
[dic9 setObject:@331 forKey:@"age"] ;
[dic9 setObject:@"mam" forKey:@"gender"] ;
NSLog( @"%@", dic9 ) ;
//修改已有键对应的值(注意:键若已存在就修改对应的值,若不存在就添加此键值对)
[dic9 setObject:@89 forKey:@"age"] ;
NSLog( @"%@", dic9 ) ;
//根据指定键去删除对应的键值对
[dic9 removeObjectForKey:@"age"] ;
NSLog( @"%@", dic9 ) ;
//删除所有的键值对
[dic9 removeAllObjects] ;
NSLog( @"%@", dic9 ) ;
时间: 2024-10-10 03:22:53