首页 > 代码库 > 黑马程序员——Foundation学习笔记(NSSet和NSMutableSet)

黑马程序员——Foundation学习笔记(NSSet和NSMutableSet)


<style></style>

==========android培训、ios培训、java培训、期待与您交流==========

一、NSSet:

 NSSet

  NSSet里面存储的元素没有顺序,NSArray中的元素有顺序。

  NSSet *s = [NSSet set]; // 创建一个空的Set,永远是空,不可变。

 

  NSSet *s2 = [NSSet setWithObjects:@"jack",@"rose",nil];

  NSString *str = [s2 anyObject]; // 随机取出一个元素

 

NSMutableSet

  NSMutableSet s = [NSMutableSet setWithObject:@"jack"];

  [s addObject:@"rose"];

  [s removeObject:(id)];

 

二、NSDictionary和NSMutableDictionary

 <1>NSDictionary

创建一个NSDictionary 不可变
NSDictionary 是没有顺序的

key ------> value
键值对

// 创建方法
NSDictionary *dict = [NSDictionary dictionaryWithObject:(id) forKey:(id<NSCopying>)];

NSDictionary *dict = [NSDictionary dictionaryWithObject:@"jack" forKey:@"name"]
[dict objectForKey:(id)];

NSLog(@"%@",obj);


创建方法二

NSArry *keys = @[@"name",@"adress"];
NSArry *values = @[@"jack",@"北京"];

NSDictionary *dict = [NSDictionary dictionaryWithObjects:values forKeys:keys];

创建方法三:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
@"jack",@"name",
@"北京",@"adress",
@"351868695",@"qq",
nil];
id obj = dict objectForKey:@"qq"];

创建方法四:
编译器特性:
// 注意返回NSDictionary类型 创建可变字典不能用这中方法
NSDictionary *dict = @{@"name" : @"jack",@"adress" : @"北京"};

id obj = dict[@"name"];
NSLog(@"%@",obj);

dict.count;// 返回键值对的个数





<2>NSMutableDictionary

NSMutableDictionary *dict = [NSMutableDictionary dictionary];

[dict setObject:@"jack" forKey:@"name"];
[dict setObject:@"北京" forKey:@"adress"];

[dict setObject:@"rose" forKey:@"name"]; // 把jack覆盖,
dict.count ;// 还是2 因为 rose覆盖了jack

[dict removeObjectForKey:(id)];


打印字典:
NSLog(@"%@",dict);结果是

{
adress = \U5317\U4eac;
name = rose;
}


字典的遍历
方法一:
NSDictionary *dict = @{@"qq" : "123",@"name" : @"jack"};
NSArray *keys = [dict allKeys]; // 该方法把字典中所有的key返回来,存到一个数组中,注意这里是无序的
for(int i = 0; i<dict.count; i++)
{
NSString *key = keys[i];
NSString *object = dict[key]; // 根据key的值取出value

NSLog(@"%@ = %@",key,object);
}

方法二:

[dict enumerateKeysAndObjectsUsingBlock:
^(id key, id obj,BOOL *stop){
NZLog(@"%@ - %@",key, obj);
}];


<style></style>

==========android培训、ios培训、java培训、期待与您交流==========