iOS基础学习

Objective-C基础学习之NSDictionary基本概念

2017-10-25  本文已影响30人  WenJim

1.NSDictionar基本概念

2.NSDictionary的创建

+ (instancetype)dictionary;
+ (instancetype)dictionaryWithObject:(id)object forKey:(id <NSCopying>)key;
+ (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ...;
+ (id)dictionaryWithContentsOfFile:(NSString *)path;
+ (id)dictionaryWithContentsOfURL:(NSURL *)url;
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:@"cwj", @"name", @"1300525003", @"phone", @"天朝", @"address", nil];
NSDictionary *dict = @{@"name":@"cwj", @"phone":@"1300525003", @"address":@"天朝"};
[dict objectForKey:@"name”];
dict[@"name”];

3.NSDictionary的遍历

    NSDictionary *dict = @{@"name":@"cwj", @"phone":@"1300525003", @"address":@"天朝"};
    for (NSString *key in dict) {
        NSLog(@"key = %@, value = %@", key, dict[key]);
    }
    [dict enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
        NSLog(@"key = %@, value = %@", key, obj);
    }];

4.NSDictionary文件操作

    NSDictionary *dict = @{@"name":@"cwj", @"phone":@"1300525003", @"address":@"天朝"};
    BOOL flag = [dict writeToFile:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/demo文件保存/NSDictionary.plist" atomically:YES];
    NSLog(@"flag = %i", flag);
NSDictionary *newDict = [NSDictionary dictionaryWithContentsOfFile:@"/Users/WJim/Desktop/Objective-CJiChuXueXi/Day7/demo文件保存/NSDictionary.plist"];
    NSLog(@"newDict = %@", newDict);
上一篇 下一篇

猜你喜欢

热点阅读