Obj-C 语言学习 笔记(III)Obj-C 中的集合类

Obj-C中的集合类有三种:集合Set,数组Array,字典Dictionary

集合满足集合内元素的互异性,无序性

Obj-C中的集合与C++和JAVA不同,它是弱类型的。不同类型的对象可以被放进同一个集合中。

Obj-C中的集合有分可变集合和不可变集合,加起来共6种:

NSSet       NSMutableSet

NSArray       NSMutableArray

NSDictionary     NSMutableDictionary

他们都具有类似的声明,初始化,元素操作和访问方法

1. NSSet 和 NSMutableSet

//声明方法为 setWithObjects, 不同的对象用逗号隔开,以nil结束
//以nil结束这点也被采用于其他所有集合类的声明里
NSSet *firstSet = [NSSet setWithObjects:@"123", @"456", @"789", nil];

//通过遍历访问:
for (id element in firstSet){
     NSLog(@"%@ 
", element);
}

//可变集合的声明和初始化
NSMutableSet *directors = [[NSMutableSet alloc] init];

//可变集合中添加元素
[directors addObject:@"Quentin Tarentino"];
[directors addObject:@"Christopher Nolan"];
[directors addObject:@"Hou Hsiao Hsien"];
[directors addObject:@"Michael Wang"];
[directors addObject:@"Quentin Tarentino"];

//用相同的元素作为参数让程序从集合中移走该元素        
[directors removeObject:@"Michael Wang"];

2. NSArray 和 NSMutableArray

//声明与初始化
NSArray *firstArray = [NSArray arrayWithObjects:@"246", @"135", nil];

//通过序号访问元素 objectAtIndex
NSLog(@"%@", [firstArray objectAtIndex:1]);

//声明可变数组
NSMutableArray *movieGenre = [[NSMutableArray alloc] init];

//向可变数组添加元素 addObject
[movieGenre addObject:@"Love"];
[movieGenre addObject:@"Thriller"];
[movieGenre addObject:@"Drama"];
[movieGenre addObject:@"Western"];
        
//像已经添加好元素的数组插入数组 insertObject: (Object) atIndex: (NSUInteger)
[movieGenre insertObject:@"Documentary" atIndex:0];

//移去元素有几种方法:
//根据序号,根据元素,移去最后一位        
[movieGenre removeObjectAtIndex:2];
[movieGenre removeObject:@"Thriller"];
[movieGenre removeLastObject];
        
for(id genre in movieGenre){
     NSLog(@"%@
", genre);
}

3. NSDictionary 和 NSMutableDictionary

//NSDictonary声明 dictonaryWithObjectsAndKeys 注意对象放在前面,Key放在后面
NSDictionary *firstDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   @"obj1", @"1",
                                   @"obj2", @"2",
                                   @"obj3", @"3", nil];

NSLog(@"%@", [firstArray objectAtIndex:1]);

//另外也可以用这种方式来声明,但就只能声明一个
NSDictionary *someDict = [NSDictionary dictionaryWithObject:@"obj1" forKey:@1];

//NSMutableDictionary的声明,假设我们总记不住一些热门电影的摄影导演的名字,想要通过电影的名称来索引摄影导演的名字。那导演名字是value,电影名是key
NSMutableDictionary *DPsFamousWork = [[NSMutableDictionary alloc] init]; //加入字典项 [DPsFamousWork setObject:@"Andrzej Sekula" forKey:@"Pulp Fiction"]; [DPsFamousWork setObject:@"Hoyte Van Hoytema" forKey:@"Interstellar"]; [DPsFamousWork setObject:@"Roger Deakins" forKey:@"Sicario"]; [DPsFamousWork setObject:@"Emmanuel Lubezki" forKey:@"The Revenant"]; //根据电影名移除某项 [DPsFamousWork removeObjectForKey:@"The Revenant"]; //根据电影名访问某项 NSLog(@"%@", [DPsFamousWork objectForKey:@"Sicario"]);
原文地址:https://www.cnblogs.com/wangsta/p/5225597.html