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