对比Java,ObjectC中的类型目前我认识到的要复杂一些。Java中的集合类型包括数组、List、Set、Map等等。。。我们下面一步一步看看ObjectC中的集合类型。
数组类型
ObjectC中的数组类型包括两种:C格式的和ObjectC格式的。
C格式的数组
C格式的数据类型如下:
int array[5] = {1, 2, 3, 4, 5}; NSLog(@"the 2nd number of the array is %i", array[1]); NSString *arrayStr[5] = {@"America", @"Britain", @"China", @"Dutch", @"Egypt"}; NSLog(@"the 2nd number of the array is %@", arrayStr[1]);
ObjectC格式的NSArray数组
示例代码如下:
NSArray *array02 = [[NSArray alloc] initWithObjects:@"America", @"Britain", @"China", @"Dutch", @"Egypt", nil]; NSLog(@"the 2nd number of the array is %@", [array02 objectAtIndex:1]); array02 = [NSArray arrayWithObjects:@"America", @"Britain", @"China", @"Dutch", @"Egypt", nil]; NSLog(@"the 2nd number of the array is %@", [array02 objectAtIndex:1]);
ObjectC格式的NSMutableArray
示例代码如下:
NSMutableArray *array03 = [[NSMutableArray alloc] initWithObjects:@"America", @"Britain", @"China", @"Dutch", @"Egypt", nil]; NSLog(@"the 2nd menber of the array is %@", [array03 objectAtIndex:1]); array03 = [NSMutableArray arrayWithObjects:@"America", @"Britain", @"China", @"Dutch", @"Egypt", nil]; NSLog(@"the 2nd menber of the array is %@", [array03 objectAtIndex:1]); [array03 addObject: @"France"]; [array03 removeObjectAtIndex:1]; NSLog(@"the 2nd menber of the array is %@", [array03 objectAtIndex:1]); // 显示最后一个元素 NSLog(@"the last menber of the array is %@", [array03 objectAtIndex:[array03 count] - 1]);
Dictionary类型
dictionary相当于java中的set,采用key-value键值对的形式。
NSDictionary
示例演示给NSDictionary赋值和通过键获取值:
NSDictionary *dic01 = [NSDictionary dictionaryWithObjectsAndKeys:@"America", @"us", @"Britain", @"uk", @"China", @"cn", nil]; NSLog(@"the selected element is %@", [dic01 objectForKey:@"us"]);
有NSDictionary,那么也有可变的NSMutableDictionary,下面演示赋值、添加元素、删除元素、查找元素:
NSMutableDictionary *dic02 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"America", @"us", @"Britain", @"uk", @"China", @"cn", nil]; [dic02 setObject:@"France" forKey:@"fr"]; [dic02 removeObjectForKey:@"us"]; NSLog(@"the selected element is %@", [dic02 objectForKey:@"fr"]);
快速枚举
实际上ObjectC的这些功能对于有过C++或者Java经验的我来说理解上会存在一定的障碍。尽管我能知晓代码是如何写出来的并且能够理解代码的含义,但我始终觉得在没有加入泛型的情况下使用ObjectC中的快速枚举有些许的不够严谨。我们继续查看代码。下面是一个对于Dictionary使用快速枚举的例子:
NSMutableDictionary *dic02 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"America", @"us", @"Britain", @"uk", @"China", @"cn", nil]; for (NSString *nation in dic02) { NSLog(@"the selected element is %@, and fullname is %@", nation, [dic02 objectForKey: nation]); } [dic02 setObject:@"France" forKey:@"fr"]; [dic02 removeObjectForKey:@"us"]; for (NSString *nation in dic02) { NSLog(@"the selected element is %@, and fullname is %@", nation, [dic02 objectForKey: nation]); }