NSDictionary的常見用法總結
NSArray *array1 = [NSArray arrayWithObjects:@"iphone",@"ipod",nil];
NSArray *array2 = [NSArray arrayWithObjects:@"mac",@"imac",@"mac pro",nil];
//類方法初始化自動釋放
NSDictionary *myDictionary = [NSDictionary dictionaryWithObjectsAndKeys:array1,@"mobile",array2,@"computers",nil];//注意用nil結束
NSLog(@"myDictionary = %@",myDictionary);
int dictSize = [myDictionary count];
//訪問字典中的值
NSArray *mobile = [myDictionary objectForKey:@"mobile"];
//從一個對象獲取鍵
NSArray *keys = [myDictionary allKeysForObject:array1];
//獲取字典中所有值得一個數組
NSArray *values = [myDictionary allValues];
//快速枚舉
for(id key in myDictionary)
{
NSLog(@"key: %@,value: %@",key,[myDictionary objectForKey:key]);
}
//如果字典只包含屬性列表對象(NSData,NSDate,NSNumber,NSString,NSArray或NSDictionary)可以保存到文件中
NSString *filePath = [[[NSBundlemainBundle]resourcePath]stringByAppendingPathComponent:@"dict.txt"];
BOOL success = [myDictionary writeToFile:filePath atomically:YES];
//用文件填充
NSDictionary *myDict2 =[NSDictionary dictionaryWithContentsOfFile:filePath];
//可變字典
NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc]initWithObjectsAndKeys:array1,@"mobile",array2,@"computer", nil];
NSString *string4 = @"stringTV";
//修改對象
[dictMutable setObject:string4 forKey:@"media"];
//刪除對象
[dictMutable removeObjectForKey:@"mobile"];
//刪除多個對象
NSArray *keyArray =[NSArray arrayWithObjects:@"mobile",@"computer", nil];
[dictMutable removeObjectForKey:keyArray];
//刪除所有對象
[dictMutable removeAllObjects];