#import <Foundation/Foundation.h>
#import "Person.h"
int main(int argc, const char * argv[]) {
@autoreleasepool {
//字典用大括号赋值
//字典是无序的 系统会自动对其key排序
//字典的创建
NSDictionary *dic3 =@ {
@"key1":@"value1",
@"key2":@"value2",
@"key3":@"value3"
};
NSLog(@"%@",dic3);
// NSDictionary *dics = [NSDictionary new];
// NSDictionary *dics = [[NSDictionary alloc] init];
// NSDictionary *dics = [NSDictionary dictionary];
//字典的初始化:- (instancetype)initWithObjectsAndKeys:(id)firstObject, ...
NSDictionary *dic1= [[NSDictionary alloc]initWithObjectsAndKeys:@"value1",@"key1",@"value2",@"key2", nil];// 先写值再写键;
NSLog(@"%@",dic1);
// + (instancetype)dictionaryWithObjectsAndKeys:(id)firstObject, ... 类方法创建字典并赋值
NSDictionary *dic2=[NSDictionary dictionaryWithObjectsAndKeys:@"value",@"key" ,nil];
NSLog(@"%@",dic2);
//键值对的值是任意类型的
Person *p1 = [[Person alloc] initWithname:@"肖明瑛" andage:17];
Person *p2 = [[Person alloc] initWithname:@"吕莎" andage:19];
Person *p3 =[[Person alloc] initWithname:@"巫婷" andage:18];
Person *p4 = [[Person alloc] initWithname:@"胡琳" andage:18];
NSDictionary *dic4 = @{
@"person1":p1,
@"person2":p2,
@"person3":p3,
@"person4":p4
};
NSLog(@"%@",dic4);
//@property (readonly) NSUInteger count;获取字典中键值对的个数
NSLog(@"%lu",[dic4 count]);
//- (nullable ObjectType)objectForKey:(KeyType)aKey;根据key取出对应的value值
NSLog(@"%@",[dic4 objectForKey:@"person1"]);
//或者
NSLog(@"%@",dic4[@"person1"]);
//@property (readonly, copy) NSArray<KeyType> *allKeys;获取字典中所有的key值
NSArray *array2 = [dic4 allKeys];
NSLog(@"%@",array2);
//获取所有的value值
NSArray *array3 = [dic4 allValues];
NSLog(@"%@",array3);
//- (NSArray<KeyType> *)allKeysForObject:(ObjectType)anObject;根据value值取出key值 可能不止一个
NSArray *array = [dic4 allKeysForObject:p1];
NSLog(@"%@",array);
//可变的字典
//初始化方法:+ (instancetype)dictionaryWithCapacity:(NSUInteger)numItems; 开辟内存空间
// NSMutableDictionary *mutable=[NSMutableDictionary dictionaryWithCapacity:10 ];//每次开辟10个内存空间 用完再开辟
//NSMutableDictionary *mutable = [[NSMutableDictionary alloc] initWithCapacity:10];
//或者:+ (instancetype)dictionary;
// NSMutableDictionary *mutable2 = [NSMutableDictionary dictionary];
//NSMutableDictionary *mutable2 = [NSMutableDictionary new];
// NSMutableDictionary *mutable = [[NSMutableDictionary alloc] init];
//常用方法
// - (void)setValue:(nullable id)value forKey:(NSString *)key; 添加元素 在可变的数组中 重复的key值会覆盖前面的(相当于更改)
NSMutableDictionary *dic5 = [NSMutableDictionary dictionary];
[dic5 setValue:@"xmy" forKey:@"person5"];
NSLog(@"%@",dic5);
[dic5 setValue:@"hyt" forKey:@"person5"];
NSLog(@"%@",dic5);
//- (void)setObject:(ObjectType)anObject forKey:(KeyType <NSCopying>)aKey;添加键值对
[dic5 setObject:@"" forKey:@"person5"];
NSLog(@"%@",dic5);
//- (void)removeObjectForKey:(KeyType)aKey; 根据key值删除元素
[dic5 removeObjectForKey:@"person5"];
NSLog(@"%@",dic5);
[dic5 removeObjectsForKeys:@[@"person3",@"person2"]];//删除多个值
//- (void)removeAllObjects;删除全部元素
[dic5 removeAllObjects];
}
return 0;
}