黑马程序员 NSDictionary的介绍及基础用法

来源:互联网 发布:跟着贝尔去冒险 知乎 编辑:程序博客网 时间:2024/06/06 16:38

 NSDictionary是什么:不可变的键值对,通俗的字面理解又叫做字典

 作用:用来存储数据的,里面的每个元素都是以键值对的形式存在的。它又称为键值对,通过key与value保存数组,两者绑定在一起作为一个完整的数据。

 创建:

 + (instancetype)dictionary;

 + (instancetype)dictionaryWithObject:(ObjectType)object forKey:(KeyType <NSCopying>)key;

 */

#import <Foundation/Foundation.h>


int main(int argc,const char * argv[]) {

    @autoreleasepool {

        NSDictionary *d=[NSDictionary dictionaryWithObject:@"zhangsan" forKey:@"zs"];

        NSLog(@"%@",d);

        NSDictionary *d1=@{@"w":@"wo",@"s":@"shi",@"r":@"ren"};//快捷创建

        NSUInteger count=d1.count;

        NSLog(@"%lu",count);

                //直接遍历

        for (NSString *keyin d1) {

            NSLog(@"%@=%@",key,d1[key]);

        }

 block遍历,block里三个参数   key:键  obj:值  *stop:控制停止

        [d1 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key,id  _Nonnull obj, BOOL * _Nonnull stop) {


            //*stop=YES;

            NSLog(@"%@=%@",key,d1[key]);

        }];

/*

 键值一一对应,若是key重复,默认输出的是第一个相对应的value

 键值对的长度.count表示有几组键值对

 利用key访问对应键的值

 运行结果:

 2016-01-27 19:25:14.453 NSDictionary[1550:96043] {

 zs = zhangsan;

 }

 2016-01-27 19:25:14.454 NSDictionary[1550:96043] 2

 Program ended with exit code: 0

 */

/Users/apple/Desktop/2.plist

        BOOL result=[d1 writeToFile:@"/Users/apple/Desktop/2.plist" atomically:YES];//字典写入

        if (result) {

            NSLog(@"success");

        }

        else{

            NSLog(@"fail");

        }

       NSDictionary *d2= [NSDictionary dictionaryWithContentsOfFile:@"/Users/apple/Desktop/2.plist"];//字典读取

        NSLog(@"%@",d2);

    }

    return0;

}


0 0