IOS SDK詳解之NSDictionary

來源:互聯網
上載者:User

IOS SDK詳解之NSDictionary

原創Blog,轉載請註明出處
blog.csdn.net/hello_hwc

前言:本文將要講述的內容有
1.NSDictionary 以及 NSMutableDictionary 概述
2.常用屬性方法舉例(不常用的本文不會涉及)

一 NSDictionary/NSMutableDictionary概述
NSDictionary提供了一種key-value的資料存放區方式。總的來說,任何對象都可以作為key,只要其遵循NSCopying協議。其中,key不能相同(由isEqual來判斷)。key和value都不能為nil,如果要表達一個空的值,用NSNull。NSDictionary中的值不可變。
NSMutableDictionary是NSDictionary的子類,是可變的字典。

二 NSDictionary常用的屬性方法舉例

2.1 建立和初始化
建立兼初始化

(instancetype)dictionaryWithContentsOfFile:(NSString *)path(instancetype)dictionary;(instancetype)dictionaryWithDictionary:(NSDictionary *)(instancetype)dictionaryWithObjects:(NSArray *)objects   forKeys:(NSArray *)keys(instancetype)dictionaryWithObjectsAndKeys:(id)firstObject

初始化

-(NSDictionary *)init;-(NSDictionary *)initWithContentsOfFile:(NSString *)path;-(NSDictionary *)initWithDictionary:(NSDictionary *);-(NSDictionary *)initWithObjects:(NSArray *)objects   forKeys:(NSArray *)keys;-(NSDictionary *)initWithObjectsAndKeys:(id)firstObject;

就個人而言,我比較習慣後一種。當然,快捷建立的方式不要忘記了
符號

@{}

舉例:

    NSDictionary * emptyDic = [NSDictionary dictionary];    NSDictionary * firstDic = @{@"key":@"value",                                @"first":@"1"};    NSDictionary * secondDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2",nil];

2.2 count
返回key-value對的個數

    NSDictionary * dic = @{@"key1":@"1",                           @"key2":@"2"};    NSLog(@"%d",dic.count);

2.3 isEqualToDictionary比較兩個dictionary內容是否一樣。

    NSDictionary * dic1 = @{@"key1":@"1",                           @"key2":@"2"};    NSDictionary * dic2 = @{@"key2":@"2",                            @"key1":@"1"};    if ([dic1 isEqualToDictionary:dic2]) {        NSLog(@"Equal contents");    }

2.4 objectForKey: 和valueForKey 由屬性獲得內容

    NSDictionary * dic1 = @{@"key1":@"1",                           @"key2":@"2"};    NSLog(@"%@",[dic1 objectForKey:@"key1"]);    NSLog(@"%@",[dic1 valueForKey:@"key2"]);

2.5 allKeys 和 allValues 獲得所有的key/value

    NSDictionary * dic1 = @{@"key1":@"1",                           @"key2":@"2"};    NSArray * keys = [dic1 allKeys];    NSArray * values = [dic1 allValues];

2.6 enumerateKeysAndObjectsUsingBlock 用Block的方式遍曆

這裡的stop決定了是否停止遍曆。NSDictionary * dic1 = @{@"key1":@"1",                           @"key2":@"2"};[dic1 enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {        NSLog(@"%@=>%@",[key description],[obj description]);    }];

2.7 排序
keysSortedByValueUsingSelector:
keysSortedByValueUsingComparator :
keysSortedByValueWithOptions: usingComparator:
返回Keys的數組,順序按照value排序次序。

  NSDictionary * numsDic = @{@(2):@"second",                               @(1):@"first",                               @(3):@"thrid"};    NSDictionary * strDic = @{@"id_1":@"first",                              @"id_3":@"thrid",                              @"id_2":@"second"};    NSArray * numsSortedKeys = [numsDic keysSortedByValueUsingSelector:@selector(compare:)];    NSArray * strSortedKyes = [strDic keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2) {        NSString * str1 = obj1;        NSString * str2 = obj2;        return [str1 compare:str2];    }];    NSLog(@"%@",numsSortedKeys.description);    NSLog(@"%@",strSortedKyes.description);

輸出

2015-02-09 22:04:12.070 DictonaryExample[1037:23292] (
1,
2,
3
)
2015-02-09 22:04:12.070 DictonaryExample[1037:23292] (
“id_1”,
“id_2”,
“id_3”
)

2.8 過濾
keysOfEntriesPassingTest:
返回keys的集合,這些keys符合參數block的約束

  NSDictionary * numsDic = @{@(2):@"second",                               @(1):@"first",                               @(3):@"thrid"};  NSSet * filteredKyes = [numsDic keysOfEntriesPassingTest:^BOOL(id key, id obj, BOOL *stop) {        BOOL result = NO;        NSNumber * numKey = key;        if (numKey.integerValue > 2) {            result =  YES;        }        return result;    }];    NSLog(@"%@",filteredKyes.description);

輸出

2015-02-09 22:09:50.800 DictonaryExample[1099:25241] {(
3
)}

2.9寫到檔案
writeToFile:atomically
writeToURL:atomically

   NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] ;    NSString * fileName = @"file";    NSString * filePath = [path stringByAppendingPathComponent:fileName];    NSDictionary * dic = @{@"key":@"value"};    BOOL result = [dic writeToFile:filePath atomically:YES];    if (result) {        NSLog(@"Success");    }

2.10Description-常常用來debug輸出dictionary的內容。
在之前已經舉例好多了,這裡不再贅述

三 NSMutableDictionary的額外方法
3.1 添加元素

- (void)setObject:(id)anObject           forKey:(id)aKey- (void)setValue:(id)value          forKey:(NSString *)key- (void)setDictionary:(NSDictionary *)otherDictionary

注意,使用KVC的時候,key一定要是NSString。第三個函數是刪除之前的元素,然後把otherDictionary元素放到當前dic中。
舉例

    NSMutableDictionary * dic = [[NSMutableDictionary alloc] initWithObjectsAndKeys:@"object",@"key", nil];    NSLog(@"%@",dic.description);    [dic setDictionary:@{@"otherKey":@"otherValue"}];    NSLog(@"%@",dic.description);

輸出

2015-02-09 22:31:21.417 DictonaryExample[1232:31666] {
key = object;
}
2015-02-09 22:31:21.418 DictonaryExample[1232:31666] {
otherKey = otherValue;
}

3.2刪除元素

- (void)removeObjectForKey:(id)aKey- (void)removeAllObjects- (void)removeObjectsForKeys:(NSArray *)keyArray

比較容易忽視的是第三個,刪除一組key。
舉例

 NSDictionary * dic = @{@(1):@"first",                           @(2):@"second",                           @(3):@"thrid"};    NSMutableDictionary * mutableDic = [[NSMutableDictionary alloc] initWithDictionary:dic];    [mutableDic removeObjectsForKeys:@[@(1),@(2)]];    NSLog(@"%@",mutableDic.description);

輸出

2015-02-09 22:34:13.112 DictonaryExample[1273:32793] {    3 = thrid;}

BTY:年前計劃在更新一篇KVC 和 KVO的詳細講解。然後繼續更新GCD系列的第五篇。如果精力夠用的話,更再更新一篇Swift相關的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.