Objective-C Foundation架構實踐——NSDictionary(一)__foundation

來源:互聯網
上載者:User

     字典是OC中一種特殊的類型,功能非常強大。是Foundation中的重要組成部分。我們來學習一下:

#import <Foundation/Foundation.h>int main(int argc, const char * argv[]) {  @autoreleasepool {      // insert code here...            /*     字典:     1.儲存的記憶體不是連續的;     2.用key和value進行對應(索引值);     3.KVC:索引值編碼;     */        //建立方式1;    NSDictionary *dict = [NSDictionary dictionaryWithObject:@"1" forKey:@"a"];    NSLog(@"%@",dict);        //建立方式2:    NSArray *arrValue = [[NSArray alloc] initWithObjects:@"1",@"2",@"3",@"4", nil];    NSArray *arrKeys = [[NSArray alloc] initWithObjects:@"a",@"b",@"c",@"d", nil];    NSDictionary *dict1 = [NSDictionary dictionaryWithObjects:arrValue forKeys:arrKeys];    NSLog(@"%@",dict1);               //建立方式3:簡便建立方式;    //@{} ;表示字典;!!!!!    NSDictionary *dict3 = @{@"1":@"a",@"2":@"b"};    NSLog(@"%@",dict3);            //長度:    int count = (int)dict3.count;    NSLog(@"count = %d",count);                //根據鍵擷取值    NSString *str = [dict3 objectForKey:@"2"];    NSLog(@"索引值 = %@",str);    //也可以使用下面的方法:    NSString *str2 = [dict3 valueForKey:@"2"];    NSLog(@"索引值 = %@",str2);            //擷取字典中的所有值;(value)    NSArray *arr5 = [[NSArray alloc] initWithObjects:@"1",@"2", @"3",nil];    NSArray *arrAllValue = [dict3 objectsForKeys:arr5 notFoundMarker:@"none"];    NSLog(@"所有值方法1 = %@",arrAllValue);        //還有一種擷取所有值的方法;    NSArray *arrAllValue2 = [dict3 allValues];    NSLog(@"所有值方法2 = %@",arrAllValue2);            //擷取字典中的所有鍵;(key)    NSArray *arrAllKey = [dict3 allKeys];    NSLog(@"所有鍵 = %@",arrAllKey);            //遍曆數組;    //需要使用鍵去遍曆;    for (NSString *key in dict3) {      NSString *value = [dict3 objectForKey:key];      NSLog(@"key = %@,value = %@",key,value);          }                //使用迭代器進行遍曆;    NSEnumerator *en = [dict3 keyEnumerator];    id key = nil;    while (key = [en nextObject]) {            NSString *str = [dict3 objectForKey:key];      NSLog(@"迭代器擷取值 = %@",str);          }              }    return 0;}

輸出結果如下:

.


github首頁:https://github.com/chenyufeng1991  。歡迎大家訪問。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.