objective-c dictionary
dictionary是由键-对象组成的数据集合。正如在词典中查找单词的定义一样,可通过对象的键从objective-c词典中获取所需的值。
词典中的键必须是单值的,尽管它们通常是字符串,但还可以是任何对象类型。和键关联的值可以是任何对象类型,但它们不能为nil。
下面是一个使用词典的类:
1 #import <Foundation/NSDictionary.h>
2 #import <Foundation/NSObject.h>
3 #import <Foundation/NSString.h>
4 #import <Foundation/NSAutoreleasePool.h>
5
6 int main(int argc, const char *argv[])
7 {
8 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9
10
11
12 //immutable dictionary
13 NSDictionary *tires = [NSDictionary dictionaryWithObjectsAndKeys :
14 @"front-left",@"t1" , @"front-right",@"t2" ,
15 @"back-left",@"t3" , @"back-right",@"t4" ,nil];
16
17 //display immutable dictionary
18 NSLog(@"t1: %@",[tires objectForKey: @"t1"]);
19 NSLog(@"t2: %@",[tires objectForKey: @"t2"]);
20 NSLog(@"t3: %@",[tires objectForKey: @"t3"]);
21 NSLog(@"t4: %@",[tires objectForKey: @"t4"]);
22
23 //mutable dictionary
24 NSMutableDictionary *glossary = [NSMutableDictionary dictionary];
25
26 //Store three entries in the glossary
27 //use setObject:forKey: method to set key/value
28 [glossary setObject: @"A class defined so other classes can inherit from it"
29 forKey: @"abstract class"];
30 [glossary setObject: @"To implment all the methods defined in a protocol"
31 forKey: @"adopt"];
32 [glossary setObject: @"Storing an object for later use"
33 forKey: @"archiving"];
34
35 //Retrieve and display them
36 //use objectForKey:key method to retrieve the value
37 NSLog(@"abstract class: %@",[glossary objectForKey: @"abstract class"]);
38 NSLog(@"adopt: %@",[glossary objectForKey: @"adopt"]);
39 NSLog(@"archiving: %@",[glossary objectForKey: @"archiving"]);
40
41 [pool drain];
42 return 0;
43
44 }
常用的NSDictionary方法:
+(id) dictionaryWithObjectsAndKeys: 使用键-对象{key1,obj1}、{key2,obj2}...创建词典
obj1,key1,obj2,key2,...,nil;
-(id) initWithObjectsAndKeys: 将新分配的词典初始化为键-对象对{key1,obj1}{key2,obj2}...创建词典
obj1,key1,obj2,key2...,nil;
-(unsigned int) count 返回词典中的记录数
-(NSEnumerator *) keyEnumerator 为词典中所有键返回一个NSEnumerator对象
-(NSArray *) keysSortedByVlaueUsingSelector: 返回词典中的键数组,它根据selector 指定的比较方法进行了排序
(SEL) selector
-(id) objectForKey:key 返回指定key的对象
常用的NSMutableDictionary方法:
+(id) dictionaryWithCapacity:size 使用一个初始指定的size创建可变词典
-(id) initWithCapacity:size 将新分配的词典初始化为指定的size
-(void) removeAllObjects 删除词典中所有的记录
-(void) removeObjectForKey:key 删除词曲中指定key对应的记录
-(void) setObject: obj forKey: key 向词典为key 键添加obj,如果key已存丰,则替换该值