標籤:
現在每天要抓緊的學習了,所以爭取每天能學習兩個知識點,儘快把OC學習完,然後進入開發階段! 加油.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
#pragma mark - NSDictionary
//NSDictionary
//使用initWithObjectsAndKeys:方法建立字典對象
//在對象建立過程中,一次性存入多個索引值對,值(value)在前,鍵(keys)在後,索引值之間用,號隔開,最後以nil結尾
//字典和數組不一樣,字典的內部元素是無序的內部都是由一個個條目(索引值對)組成的,所以是沒有順序的.
NSDictionary *obj1= [[NSDictionary alloc] initWithObjectsAndKeys:@"Jack",@"name",@"male",@"sex",[NSNumber numberWithInt:28],@"age", nil];
//通過key值擷取value
NSLog(@"=======通過key擷取value======");
NSString *sex = [obj1 valueForKey:@"sex"];
NSLog(@"%@",sex);
//擷取所有value
NSLog(@"=======allValue======");
NSArray *allObjectValue = [obj1 allValues];
NSLog(@"%@",allObjectValue);
//擷取所有key
NSLog(@"=======allkeys=======");
NSArray *allObjectKey = [obj1 allKeys];
NSLog(@"%@",allObjectKey);
//便利字典 便利只能便利key,然後在通過key找value
NSLog(@"=====便利=========");
for (NSString *key in obj1) {
NSLog(@"%@",[obj1 valueForKey:key]);
}
#pragma mark - NSMutableDictionary
//NSMutableDictionary
//使用便利構造器,建立可變字典對象
NSLog(@"=======1========");
NSMutableDictionary *obj2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"Henry",@"name",@"male",@"sex",@"26",@"age", nil];
NSLog(@"%@",obj2);
//字典有兩個方法來添加:
//1.通常情況下都是用setValue forKey 因為可以正常給nil
//2.也可以用setObject forKey 但如果給nil 就會Crash
//添加
[obj2 setValue:@"130" forKeyPath:@"weight"];
NSLog(@"%@",obj2);
[obj2 setObject:@"130" forKey:@"weight"];
NSLog(@"%@",obj2);
//修改
//setValue forKey 方法: 如果字典存在對應的key,那麼就回修改value的值,如果不存在對應的key,就會添加對應的索引值對,所以setValue forKey可以用來修改和添加
[obj2 setValue:@"100" forKey:@"weight"];
NSLog(@"%@",obj2);
//刪除
//刪除包含兩個方法:
//1.removeObjectForKey 例如:刪除@"sex"
[obj2 removeObjectForKey:@"sex"];
NSLog(@"%@",obj2);
//2.removeAllObjectss 刪除所有
[obj2 removeAllObjects];
NSLog(@"沒有了 %@",obj2);
//擴充題:用字典和數組表示國家,省份,城市,地區
NSDictionary *obj3 = [NSDictionary dictionaryWithObjectsAndKeys:@"China",@"Country",@"heilongjiang",@"shengfen",@"Harbin",@"City",@"acheng",@"diqu", nil];
NSDictionary *obj4 = [NSDictionary dictionaryWithObjectsAndKeys:@"America",@"Country",@"NewYork",@"NY",@"NewzeXi",@"NzX",@"abc",@"diqu", nil];
NSArray *array = [[NSArray alloc] initWithObjects:obj3,obj4, nil];
for (NSDictionary *dic in array) {
NSLog(@"%@",dic);
}
}
return 0;
}
Objective-C NSDictionary & NSMutableDictionary