NSDictionary的作用同JAVA中的字典相同,提供了“健-值”對的集合。
比如,使用字典實現員工編號到員工姓名的存放,編號是一個鍵(唯一性),姓名是值.
NSDictionary例子:
//用dictionaryWithObjectsAndkeys初始化一個靜態字典,記住以nil結束NSDictionary *employes = [NSDictionary dictionaryWithObjectsAndKeys:@"張三",@"1", @"李四",@"2",@"王五",@"3",nil];NSString *firstEmployes = [employes objectForKey:@"1"];
NSMutableDictionary例子:
//用dictionary初始化一個動態字典NSMutableDictionary *employes = [NSMutableDictionary dictionary];[employes setObject:@"張三" forKey:@"1"]; //增加一個鍵-值[employes setObject:@"李四" forKey:@"2"]; //增加一個鍵-值[employes setObject:@"王五" forKey:@"3"]; //增加一個鍵-值//輸出NSLog(@"No:1,%@",[employes objectForKey:@"1"]);NSLog(@"No:2,%@",[employes objectForKey:@"2"]);NSLog(@"No:3,%@",[employes objectForKey:@"3"]);
【程式輸出】
1,張三2,李四3,王五
NSDictionary常用方法:
+(id)dictionaryWithObjectsAndKeys:obj1,obj2,...nil //順序增加對象和索引值來建立一個字典。-(id)initWithObjectsAndKeys:obj1,key1,obj2,key2,...nil //初始化一個新分配的字典,順序增加對象和值-(unsigned int)count //返回字典中記錄數-(NSEnumerator*)keyEnumerator //返回字典中所有的鍵到一個NSEnumerator對象-(NSArray*)keysSortedByValueUsingSelector:(SEL)selector //用Selector指定的方法時行排序-(NSEnumerator*)objectEnumerator //返回字典中的值到一個NSEnumerator類型對象-(id)objectForKey:key //返回指定key的值
NSMutableDictionary常用方法:
+(id)dictionaryWithCapacity:size //建立一個size大小的可變字典-(id)initWithCapacity:size //初始化一個size大小的可變字典-(void)removeAllObjects //刪除字典中所有元素-(void)removeObjectForKey:key //刪除字典key位置的元素-(void)setObject:obj forKey:key //增加(obj,key)到字典中,若key已經存在,則替換值為obj