標籤:style blog color 使用 os io 資料 for
1.NSDictionary 和NSMutableDictionary
NSDictionary dictionaryWithObjectsAndKeys:~,nil
使用索引值對建立字典,用nil標誌結束
NSDictionary initWithObjectsAndKeys:
使用索引值對初始化字典,也用nil來表示結束.
dictionary count 計算其字典的長度.
dictionary keyEunmerator 將key全部存在NSEunmerator中,可以快速枚舉其中的key的值.
dictionary objectForKey: key 通過key來查詢值.
demo:
#import <UIKit/UIKit.h> #import "MyClass.h" int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //添加我們的測試代碼 NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"我是值",@"我是key1",@"我是值2",@"我是key2", nil]; //得到詞典的數量 int count = [dictionary count]; NSLog(@"詞典的數量為: %d",count); //得到詞典中所有KEY值 NSEnumerator * enumeratorKey = [dictionary keyEnumerator]; //快速枚舉遍曆所有KEY的值 for (NSObject *object in enumeratorKey) { NSLog(@"遍曆KEY的值: %@",object); } //得到詞典中所有Value值 NSEnumerator * enumeratorValue = [dictionary objectEnumerator]; //快速枚舉遍曆所有Value的值 for (NSObject *object in enumeratorValue) { NSLog(@"遍曆Value的值: %@",object); } //通過KEY找到value NSObject *object = [dictionary objectForKey:@"我是key2"]; if (object != nil) { NSLog(@"通過KEY找到的value是: %@",object); } int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }
2.NSMutableDictionary是NSDictionary的子類,因此也繼承其有的方法.
[NSMutableDictionary dictionaryWithCapacity:10];
//建立一個長度為10的字典,不過字典的內容超過了10會自動增加.
[NSMutableDictionary initWithCapacity: 10];//初始化長度為10;[dictionary setObject:~ forKey;~];//x向可變的字典中添加資料;[dictionary removeAllobjects];//刪除所有的資料;removeObjectForKey: //刪除key的對應值;
#import <UIKit/UIKit.h> #import "MyClass.h" int main(int argc, char *argv[]) { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; //添加我們的測試代碼 //建立詞典對象,初始化長度為10 NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:10]; //向詞典中動態添加資料 [dictionary setObject:@"被添加的value1" forKey:@"key1"]; [dictionary setObject:@"被添加的value2" forKey:@"key2"]; //通過KEY找到value NSObject *object = [dictionary objectForKey:@"key2"]; if (object != nil) { NSLog(@"通過KEY找到的value是: %@",object); } int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; }
[NSMutableDictionary dictionaryWithCapacity:10];
//建立一個長度為10的字典,不過字典的內容超過了10會自動增加.