// 1.创建字典
NSDictionary *jack = [[NSDictionary alloc] initWithObjectsAndKeys:
@"jack", @"name", @"18", @"age", nil];
// 2.快速创建字典,比较常用
NSDictionary *jack1 = @{
@"name":@"jack",
@"age":@"18"
};
NSLog(@"%p %p",jack,jack1);
NSLog(@"jack = %@ jack1 = %@",jack,jack1);
NSNumber *number = [NSNumber numberWithInt:21];
NSArray *array = @[@"one",@"two",@"three"];
// 3.在字典中存储数据时没有顺序
NSDictionary *dic = @{
@"array":array,
@"number":number,
@"dic":jack1
};
NSLog(@"dic = %@",dic);
// 4.获取字典长度
NSUInteger count = [dic count];
NSLog(@"字典长度为 = %lu",count);
// 5.从字典中取值
// Returns the value associated with a given key.
// 返回键对应的值
NSArray *arrayInDic = [dic objectForKey:@"array"];
NSLog(@"字典中的array = %@",arrayInDic);
NSDictionary *dicInDic = [dic objectForKey:@"dic"];
NSLog(@"字典中的dic = %@",dicInDic);
NSNumber *numberInDic = [dic objectForKey:@"number"];
NSLog(@"字典中的number = %@",numberInDic);
// 1.快速创建的字典和数组都是不可变的
// 值,键,值,键...
NSMutableDictionary *mutableDic = [[NSMutableDictionary alloc]initWithObjectsAndKeys:@"jack",@"name",@"18",@"age", nil];
NSLog(@"mutableDic = %@",mutableDic);
// 2.如何向字典中'插入'一个数据
Person *person = [[Person alloc]init];
NSString *string = [[NSString alloc]initWithFormat:@"18"];
// - (void)setObject:(id)anObject forKey:(id <NSCopying>)aKey;
[mutableDic setObject:person forKey:@"height"];
NSLog(@"count = %ld",[person retainCount]);// strong reference 就要释放掉
[person release];
// [string release];
NSLog(@"mutableDic = %@",mutableDic);
// The value for aKey. A strong reference to the object is maintained by the dictionary. Raises an NSInvalidArgumentException if anObject is nil.// 键对应值,字典会强引用这个对象,
// 3.删除
[mutableDic removeObjectForKey:@"name"];
NSLog(@"%@",mutableDic);
// // 4.全部删除
// [mutableDic removeAllObjects];
// NSLog(@"mutableDic = %@",mutableDic);
// 5.遍历字典
// 获取字典中所有的键
NSArray *keysArray = [mutableDic allKeys];
// 获取字典中所有的值
NSArray *valuesArray = [mutableDic allValues];
// Returns a new array containing the dictionary’s values.
//The order of the values in the array isn’t defined.
// 返回包含字典中值的新数组 数组中值的顺序没有被定义
for (id key in keysArray) {
NSLog(@"key = %@",key);
id value = mutableDic[key]; // 获取某个key的值
NSLog(@"value = %@",value);
}
//
OC总结之字典
最新推荐文章于 2023-07-20 10:47:09 发布