OC基础 Foundation基础 NSDictionary
OC中的所有集合对象(NSArry,NSSet,NSDictionary)只能存储OC对象,不能存储基本数据类型 (char short int long float double)和结构体类型数值
main
#import <Foundation/Foundation.h> int main(int argc, const char * argv[]) { @autoreleasepool { NSDictionary* dic =[NSDictionary dictionaryWithObject:@1 forKey:@"1"]; NSDictionary* dic2=@{@"1":@1,@"2":@2}; NSDictionary* dic3=[NSDictionary dictionaryWithObjectsAndKeys:@1,@"1",@2,@"2", nil]; NSArray* objs=@[@1,@2]; NSArray* keys=@[@"1",@"2"]; NSDictionary* dic4 =[NSDictionary dictionaryWithObject:objs forKey:keys]; //字典对象的使用 id obj =[dic2 objectForKey:@"2"]; NSLog(@"%@",obj); for(id key in dic3) { id obj =[dic2 objectForKey:key]; NSLog(@"%@",obj); } // 用法 联系人的信息 NSDictionary* contact = @{@"name":@"Tom",@"age":@25,@"tel":@"15645530792",@"email":@"786577908@qq.com"}; NSDictionary* contact2 = @{@"name":@"Tom2",@"age":@35,@"tel":@"156455307923",@"email":@"786577908@qq.com"}; NSMutableArray* contractbook=[[NSMutableArray alloc] init]; [contractbook addObject:contact]; [contractbook addObject:contact2]; // 并不是按照顺序 也是hash table NSLog(@"%@",contractbook); } return 0; }
拓展
// 在字典中 key必须是唯一的 不能重复 NSDictionary* contact3 = @{@"name":@"Tom",@"age":@25,@"tel":@"15645530792",@"email":@"786577908@qq.com",@"name":"Smish"}; NSLog(@"%@",contact3); // 字典中block遍历 [contact2 enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) { NSLog(@"%@:,%@",key,obj); }]; // 字典对象写到文件中 [contact2 writeToFile:<#(nonnull NSString *)#> atomically:(BOOL)]; // 通过读文件创建字典对象 NSDictionary* contract4=[NSDictionary dictionaryWithContentsOfFile:<#(nonnull NSString *)#>] // 可变的字典对象 NSMutableDictionary* mutableDic=[[NSMutableDictionary alloc]init]; [mutableDic setDictionary:contact]; //移除 [mutableDic removeObjectForKey:@"email"]; NSLog(@"%@",mutableDic); //移除多个 [mutableDic removeObjectsForKeys:@[@"age",@"tel"]]; NSLog(@"%@",mutableDic); //新增一个对象 [mutableDic setObject:@30 forKey:@"age"]; NSLog(@"%@",mutableDic);