標籤:objective 索引值 nsmutabledictionary dictionary oc
知識點:
定義:字典(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 ) ;
Objective-C----NSDictionary、NSMutableDictionary