1.字典
initWithObjectsAndKeys ; 初始化字典
dictionaryWithObjectsAndKeys : 初始化字典
dictionaryWithObjects forKeys:
1.1
NSDictionary * dic = [[NSDictionary alloc] initWithObjectsAndKeys:@"m", @"sex", @"25", @"age", @"zhangsan", @"name",nil];
NSLog(@"%@", dic);
1.2
NSDictionary * dic2 = [NSDictionary dictionaryWithObjectsAndKeys:@"zhangsan", @"name", @"21", @"age",nil];
NSLog(@"%@", dic2);
1.3
NSArray * valueArray = [NSArray arrayWithObjects:@"fulushou", @"M", @"25", nil];
NSArray * keyArray = [NSArray arrayWithObjects:@"name", @"sex", @"age", nil];
NSDictionary * dic = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
NSLog(@"%@", dic);
2.//count // allKeys //allValues // 对数 , 所有的键 , 所有的值
@property(readonly) NSUInteger count //The number of entries in the dictionary (read-only)
@property(readonly, copy) NSArray *allKeys //A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries (read-only)
例子
NSLog(@"%lu", [dic count]);
NSLog(@"%@", [dic allKeys]);
NSLog(@"%@", [dic allValues]);
3.objectForKey 通过键获取值字典中的值
- (id)objectForKey:(NSString *)key // Returns the value for the given key stored in the record.
例子
NSString * str = [dic objectForKey:@"name"];
NSLog(@"%@", str);
// 怎么遍历 字典 ? 方法一
for (int i = 0; i < [dic count]; i++) {
NSString * value = [[dic allKeys] objectAtIndex:i];
NSLog(@"%@", [dic objectForKey:value]);
}
for (int i = 0; i < [dic count]; i++) {
NSString * value = [[dic allValues] objectAtIndex:i];
NSLog(@"%@", value);
}
4.NSMutableDictionary //继承自Dictdonary 的可改变的字典
NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithCapacity:1];
5.setObject //给字典添加数据
virtual bool setObject( const char *aKey, const OSMetaClassBase *anObject); //Stores an object in the dictionary under a key.
例子
// [dic setObject:@"fulushou" forKey:@"name"];
// [dic setObject:@"M" forKey:@"sex"];
// [dic setObject:@"25" forKey:@"age"];
6.removeObjectForKey //通过key 删除字典中数据
- (void)removeObjectForKey:(NSString *)defaultName //Removes the value of the specified default key in the standard application domain.
例子
[dic removeObjectForKey:@"age2"];
NSLog(@"%@", dic);
7.arrayWithObjects //批量删除字典中数据
+ (instancetype)arrayWithObjects:(id)firstObj , ... //Creates and returns an array containing the objects in the argument list.
NSArray * arr = [NSArray arrayWithObjects:@"age", @"sex", nil];
[dic removeObjectsForKeys:arr];
NSLog(@"%@", dic);
8.removeAllObjects //清空字典
- (void)removeAllObjects // Empties the cache.
例子
[dic removeAllObjects];
NSLog(@"%@", dic);