dictionary是由鍵-對象組成的資料集合。正如在詞典中尋找單詞的定義一樣,可通過對象的鍵從objective-c詞典中擷取所需的值。
詞典中的鍵必須是單值的,儘管它們通常是字串,但還可以是任何物件類型。和鍵關聯的值可以是任何物件類型,但它們不能為nil。
下面是一個使用詞典的類:
#import <Foundation/NSDictionary.h><br />#import <Foundation/NSObject.h><br />#import <Foundation/NSString.h><br />#import <Foundation/NSAutoreleasePool.h></p><p>int main(int argc, const char *argv[])<br />{<br /> NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];</p><p> //immutable dictionary<br /> NSDictionary *tires = [NSDictionary dictionaryWithObjectsAndKeys :<br /> @"front-left",@"t1" , @"front-right",@"t2" ,<br /> @"back-left",@"t3" , @"back-right",@"t4" ,nil];</p><p> //display immutable dictionary<br /> NSLog(@"t1: %@",[tires objectForKey: @"t1"]);<br /> NSLog(@"t2: %@",[tires objectForKey: @"t2"]);<br /> NSLog(@"t3: %@",[tires objectForKey: @"t3"]);<br /> NSLog(@"t4: %@",[tires objectForKey: @"t4"]);</p><p> //mutable dictionary<br /> NSMutableDictionary *glossary = [NSMutableDictionary dictionary];</p><p> //Store three entries in the glossary<br /> //use setObject:forKey: method to set key/value<br /> [glossary setObject: @"A class defined so other classes can inherit from it"<br /> forKey: @"abstract class"];<br /> [glossary setObject: @"To implment all the methods defined in a protocol"<br /> forKey: @"adopt"];<br /> [glossary setObject: @"Storing an object for later use"<br /> forKey: @"archiving"];</p><p> //Retrieve and display them<br /> //use objectForKey:key method to retrieve the value<br /> NSLog(@"abstract class: %@",[glossary objectForKey: @"abstract class"]);<br /> NSLog(@"adopt: %@",[glossary objectForKey: @"adopt"]);<br /> NSLog(@"archiving: %@",[glossary objectForKey: @"archiving"]);</p><p> [pool drain];<br /> return 0;</p><p>}<br />
常用的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已存豐,則替換該值