博客> 10.NSDictionary
10.NSDictionary
2018-07-20 22:07 评论:0 阅读:443 Longer_Tao
oc NSDictionary
/********************************** NSDictionary **********************************/
// 注意事项:
// 特点:  
//   键值对集合的特点
//   字典存储的时候,必须是"键值对"的方式来存储(同时键不要重复)
//   键值对中存储的数据是"无序的".
//   键值对集合可以根据键, 快速获取数据.

#pragma mark 1.NSDictionary的创建

 + (instancetype)dictionary;
 + (instancetype)dictionaryWithObject:(id)object forKey:(id <NSCopying>)key;
 + (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
 + (id)dictionaryWithContentsOfFile:(NSString *)path;
 + (id)dictionaryWithContentsOfURL:(NSURL *)url;

// NSDictionary创建简写
 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"lnj", @"name", @"12345678", @"phone", @"天朝", @"address", nil];
 // 简写
 NSDictionary *dict = @{@"name":@"lnj", @"phone":@"12345678", @"address":@"天朝"};

// NSDictionary获取元素简写
 [dict objectForKey:@"name”];
 // 简写
 dict[@"name”];```

```objc
#pragma mark 2.NSDictionary的读取和遍历
 // 返回字典的键值对数目
 - (NSUInteger)count;

 // 根据key取出value
 - (id)objectForKey:(id)aKey;

 // 快速遍历
    NSDictionary *dict = @{@"name":@"lnj", @"phone":@"12345678", @"address":@"天朝"};
    for (NSString *key in dict) {
        NSLog(@"key = %@, value = %@", key, dict[key]);
    }

 // Block遍历
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
        NSLog(@"key = %@, value = %@", key, obj);
    }];

#pragma mark 3.NSDictionary文件操作
// 1> 将字典写入文件中
 - (BOOL)writeToFile:(NSString *)path atomically:(BOOL)useAuxiliaryFile;
 - (BOOL)writeToURL:(NSURL *)url atomically:(BOOL)atomically;
// 存结果是xml文件格式,但苹果官方推荐为plist后缀。

// 示例:
    NSDictionary *dict = @{@"name":@"lnj", @"phone":@"12345678", @"address":@"天朝"};
    BOOL flag = [dict writeToFile:@"/Users/LNJ/Desktop/dict.plist" atomically:YES];
    NSLog(@"flag = %i", flag);

// 2> 从文件中读取字典
 NSDictionary *newDict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/LNJ/Desktop/dict.plist"];
    NSLog(@"newDict = %@", newDict);```
收藏
0
sina weixin mail 回到顶部