NSDictionary和NSMutableDictionary的相关总结

来源:互联网 发布:毁灭战士4优化补丁 编辑:程序博客网 时间:2024/06/13 01:37

NSDicionary

/* 存储的内存不是连续的,用key和value进行对应(键值),Kvc 键值编码*/

NSDictionary *dict1 = [NSDictionary   dictionaryWithObject:@”1” forKey:@”a”];//键值对

NSLog(@”dict1 = %@”, dict1);//运行结果如下:

Dict1 = {

  a =1;

}//注意是大括号,数组是小括号

 

NSDictionary *dict2 = [NSDictionary  dictionaryWithObjects:[NSArray  arrayWithObjects:@”1”,@”2”,@”3”,  nil] forKeys:[NSArray arrayWithObjects:@”a”,@”b”,@”c”,nil]];

NSLog(@”%@”,dict2);//运行结果如下

Dict2 = {

  a =1;

  b =2;

  C =3;

}//注意是大括号,数组是小括号

 

NSDictionary *dict3 = @{@”1”:@”a”,@”2”,@”b”};

NSLog(@”dict3 = %@”, dict3);//运行结果如下:

Dict3 ={

   1= a;

   2= b;

}//注意这种方式是Key在前,值在后,和之前的几种方式不一样

 

//字典数据数目

int count = (int)[dict2 count];

NSLog(@”count = %d”, count);//运行结果为:count = 3

//取值

NSString *Value = [dict2 valueForKey:@”b”];

NSLog(@”value = %@”, value);

//取值

NSString *value2 = [dict2 objectForKey:@”b”];

NSLog(@”value2 = %@”,value);

//取全部值

NSArray *allValues = [dict2 allValues];

NSLog(@”allValues = %@”,allValues);

//取全部key

NSArray *allKeys = [dict2 allKeys];

NSLog(@”allKeys = %@”, allKeys);


//以下方法了解一下,没有key的用notFoundMarker后面的字符串代替

NSArray *array = [dict2 objectsForKeys:[NSArray arrayWithObjects:@”a”,@”b”,@”d”,nil]

notFoundMarker:@”not fount”];

NSLog(@”array = %@”, array);//输入结果如下

Array = (

   1,

   2,

   “notfount”

)

 

//遍历字典

for(NSString * key in dict2)//遍历dict2里面所有的KEY,字典需要key来遍历,通过key获取值

{

NSLog(@”%@ = %@”, key, [dict2 objectForKey: key]);

}//运行结果如下:
a = 1

b = 2

c = 3

//遍历字典枚举器

NSEnumerator *en = [dict2 keyEnumerator];

id  key = nil;

While(key = [en nextObject]){

 NSLog(@”key - %@”, key);

}//运行结果如下

Key - a

Key - b

Key- c

 

/*[dict2  enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){

}]*/

 

//可变字典 NSMutableDictionary

NSMutableDictionary *dict =[[NSMutableDictionary alloc] init];

//添加键值对

[dict setObject:@”1” forKey:@”a”];

[dict setObject:@”1” forKey:@”b”];

//删除键值对

//[dict removeAllObjects];

//[dict removeObjectForKey:@”b”];

//[dict removeObjectsForKeys:[NSArray  arrayWithObjects:@”a”,@”b”, nil]];

NSLog(@”dict = %@”,dict);

0 0
原创粉丝点击