- 不要等到明天,明天太遥远,今天就行动。
须读:看完该文章你能做什么?
NSDictionary的基本使用
学习前:你必须会什么?(在这里我已经默认你具备C语言的基础了)
适合所有人,不需要懂的什么
注:(小白直接上手)
一、本章笔记
key(标识) 为了方便查找那个值
一、字典
1.如何创建
+ (instancetype)dictionaryWithObject:(ObjectType)object forKey:(KeyType <NSCopying>)key;
+ (instancetype)dictionaryWithObjects:(NSArray<ObjectType> *)objects forKeys: (NSArray<KeyType <NSCopying>> *)keys;
获取
- (nullable ObjectType)objectForKey:(KeyType)aKey;
2.字典的三种遍历方式
2.1 for
2.2 for in
2.3 block
- (void)enumerateKeysAndObjectsUsingBlock:(void (NS_NOESCAPE ^)(KeyType key, ObjectType obj, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
3.字典的文件读写
- (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
+ (nullable NSDictionary<KeyType, ObjectType> *)dictionaryWithContentsOfFile:(NSString *)path;
二、code
main.m
#pragma mark 08-NSDictionary
#pragma mark - 代码
#import <Foundation/Foundation.h>
#pragma mark 类
#pragma mark - main函数
int main(int argc, const char * argv[])
{
#pragma 1.如何创建
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"lyh" forKey:@"name"];
NSString *name = [dict objectForKey:@"name"];
NSLog(@"name = %@",name);
// 注意 : key 和 value 是一一对应的
NSDictionary *dict2 = [NSDictionary dictionaryWithObjects:@[@"lyh",@"25"] forKeys:@[@"name",@"age"]];
NSLog(@"%@ %@",[dict2 objectForKey:@"name"],[dict2 objectForKey:@"age"]);
#pragma 创建、获取的快捷方式
// NSDictionary *dict3 = @{key:value};
NSDictionary *dict3 = @{@"name":@"lyh"};
NSLog(@"name = %@",dict3[@"name"]);
NSDictionary *dict4 = @{@"name":@"lyh",@"age":@"25",@"height":@"171.1"};
NSLog(@"name = %@ , age = %@",dict4[@"name"],dict4[@"age"]);
#pragma 2.字典的遍历
// 方式1 for
/*
// 2.1 如何获取字典中 的 key 和 value的个数,在字典中 key称之为键, value称之为值
NSLog(@"count = %lu",[dict4 count]);
for (int i = 0 ; i < dict4.count; ++i) {
// 获取字典中所有的key
NSArray *keys = [dict4 allKeys];
// 期初当前位置对应的key
// NSLog(@"%@",keys[i]);
NSString *key = keys[i];
NSString *value = dict4[key];
NSLog(@"key = %@, value = %@",key,value);
}
*/
// 方式2 for in
/*
// 如果通过forin 遍历 ,会将所有的key赋值给前面的obj
for (NSString *key in dict4) {
NSLog(@"%@",key);
NSString *value = dict4[key];
NSLog(@"key = %@, value = %@",key,value);
}
*/
// 方式3 迭代器
[dict4 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"key = %@, value = %@",key,obj);
}];
#pragma 3.字典的文件读写
// 写
[dict4 writeToFile:@"/Users/liyuhong165/Desktop/temp/day08/abcd.plist" atomically:YES];
// 读
// 注意 : 字典 和 数组不同, 字典中保存的数据是无序的
NSDictionary *newDict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/liyuhong165/Desktop/temp/day08/abcd.plist"];
NSLog(@"newDict = %@",newDict);
return 0;
}
Person
>>>.h
>>>.m