标签:
几种常见的集合:
NSArray/NSMutableArray
NSSet/NSMutableSet
NSDictionary/NSMutableDictionary
1.不可变有序数组:
void Array()
{
// 创建
// 快速创建的方法只适于创建不可变数组
NSArray *s = @[@"jack", @"rose", @"jerry"];
//数组对象的访问
NSLog(@"%@", s[0]);
// 快速枚举
for (NSString *obj in s){
NSLog(@"%@", obj);
}
// 枚举遍历,适可而止
[s enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (idx == 1) {
*stop = YES;
}
NSLog(@"%@", obj);
}];
<pre name="code" class="objc"> // 数组中对象的个数
NSInteger count = s.count;
NSLog(@"count= %ld", count);
}
2.不可变有序数组:创建、添加、删除、遍历等
void MutableArray()
{
// 创建
NSMutableArray *s = [NSMutableArray arrayWithObjects:@"jack", @"jerry", @"jane", nil];
// 添加对象
[s addObject:@"1"];
NSArray *array = @[@"2", @"3", @"4"];
[s addObjectsFromArray:array];
// 删除对象
[s removeObject:@"jack"];
// 删除所有对象
[s removeAllObjects];
// 快速枚举遍历
for (NSString *obj in s) {
NSLog(@"%@", obj);
}
// 枚举遍历:根据条件停止遍历
[s enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
if (idx == 4) {
*stop = YES;
}
NSLog(@"%@", obj);
}];
// 输出数组中对象个数
NSLog(@"%ld", s.count);
}
3.无序不可变集合:
void set()
{
// 创建
NSSet *s = [NSSet setWithObjects:@"1", @"2", @"3", nil];
// 随机访问
NSString *str = [s anyObject];
NSLog(@"str= %@", str);
// 快速枚举,打印出来是无序的
for (NSString *obj in s) {
NSLog(@"NSSet= %@", obj);
}
// 集合对象个数
NSLog(@"count= %ld", s.count);
}
4.无序可变集合:
void mutableSet()
{
// 创建
NSMutableSet *s = [NSMutableSet setWithObjects:@"1", @"2", @"3", nil];
// 添加单个对象
[s addObject:@"4"];
// 添加多个对象
NSArray *array = @[@"5", @"6"];
[s addObjectsFromArray:array];
// 删除对象
[s removeObject:@"1"];
[s removeAllObjects];
// 枚举遍历
for (NSString *obj in s) {
NSLog(@"NSMutableSet= %@", obj);
}
}
5.无序不可变字典:
void dictionary()
{
// 创建
// 键 : 值
NSDictionary *d = @{@"61" : @"林昆", @"63" : @"小强", @"57" : @"小顺", @"59" : @"小波"};
// 访问
id obj = d[@"61"];
NSLog(@"61 -> %@", obj);
// 输出字典的键值对数
NSLog(@"键值对数:%ld", d.count);
}
6.无序可变字典:
void mutableDictionary()
{
// 创建
NSMutableDictionary *s = [NSMutableDictionary dictionary];
// 添加键值对
[s setObject:@"林昆" forKey:@"61"];
[s setObject:@"小强" forKey:@"63"];
[s setObject:@"小顺" forKey:@"57"];
[s setObject:@"小波" forKey:@"59"];
// 删除键值对
[s removeObjectForKey:@"61"];
// 访问值对象
id obj = s[@"61"];
NSLog(@"61 -> %@", obj);
// 输出键值对数
NSLog(@"键值对:%ld", s.count);
}
7.数组对象元素是字典对象:
void arrayAndDictionary()
{
// 允许有相同的value,当不允许有相同的key
NSDictionary *d = @{@"林昆" :@"123", @"小强" :@"456", @"小顺" :@"789", @"小波" :@"123"};
// 创建不可变数组元素
// 元素对象是字典集
NSArray *s = @[@{@"Name" :@"Linkun", @"QQ" :@"1245205002", @"Favourite" :@[@"Weekness Of People",@"The World Of Commond"]},
@{@"qq1" :@"123"},
@{@"qq2" :@"234"}];
// 取值
// 键值命名不能有空格
NSString *s1 = s[0][@"QQ"];
NSLog(@"取出QQ号码:%@", s1);
NSString *s2 = s[0][@"Favourite"][0];
NSLog(@"取出喜欢的书:%@", s2);
// 快速枚举遍历
for (NSString *obj in s) {
NSLog(@"%@", obj);
}
}
标签:
原文地址:http://blog.csdn.net/sziit_jerry/article/details/51334023