Objective-c的Foundation中常用類4——字典NSDictionary、NSMutableDictionary

來源:互聯網
上載者:User

Foundation中的字典是由鍵-值對組成的資料集合,好比java中的Map,在字典對象中key值必須是唯一的,另外字典對象中的鍵和值都不能為nil。,如果要在字典對象中表示一個空值,可以用NSNull對象(這裡主要指值value)。字典對象也可分為不可變字典和可變字典。

1、不可變字典

        NSNumber *num1 = [NSNumber numberWithInt:5];        NSNumber *num2 = [NSNumber numberWithInt:10];        NSNumber *num3 = [NSNumber numberWithInt:15];        //初始化一個字典        NSDictionary *dictionary = [NSDictionary dictionaryWithObject:num1 forKey:@"num"];        //通過鍵擷取值        NSObject *object = [dictionary objectForKey:@"num"];                        NSDictionary *moreNum = [NSDictionary dictionaryWithObjectsAndKeys:num1,@"num1", num2,@"num2",num2,@"num3",nil];        //將字典對象的key轉化成一個枚舉對象,用於遍曆        NSEnumerator *enumerater = [moreNum keyEnumerator];        //擷取所有的鍵        NSArray *keyArray = [moreNum allKeys];        //擷取所有的值        NSArray *valueArray = [moreNum allValues];                        //建立一個新字典,新字典包含其他字典        NSDictionary *newDic = [NSDictionary dictionaryWithDictionary:dictionary];                        //擷取字典數量        NSInteger *theNum = [newDic count];

2、可變字典NSMutableDictionary

同樣繼承自NSDictionary,所以NSDictionary中的所有方法都適用於他

//建立一個可變字典        NSMutableDictionary *mDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:num1,@"num1", num2,@"num2",num2,@"num3",nil];        //向可變字典對象中加入整個字典        NSDictionary *dic2 = [NSDictionary dictionaryWithObject:@"nihao" forKey:@"hello"];        [mDic addEntriesFromDictionary:dic2];                //向可變字典中追加一個索引值對        [mDic setValue:@"jimGreen" forKey:@"name"];                //遍曆對象,取資料        for(id key in mDic){                        id obj = [mDic objectForKey:key];            NSLog(@"%@",obj);                    }

聯繫我們

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