Objective-C字典使用詳解

乞力馬紮羅的雪CYF發表於2015-09-22
#import <UIKit/UIKit.h>
#import "AppDelegate.h"

int main(int argc, char * argv[]) {

  

  //類似Java中的Map,即鍵值對;
  NSDictionary *dict = @{@"name":@"zhangsan",@"age":@23};

  //列印出整個字典;
  NSLog(@"%@",dict);
  
  //取出字典中的某個值;
  NSLog(@"%@",[dict objectForKey:@"name"]);
  
  //讀取一個plist字典;
  //plist檔案可以作為配置檔案,可以儲存陣列或者字典。類似Android中的XML配置檔案。需要好好使用!
  NSDictionary *plistDict = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"]];
  NSLog(@"Plist檔案中的字典:%@",plistDict);
  NSLog(@"Plist中的年齡:%@",[plistDict objectForKey:@"age"]);
  
  
}


輸出結果如下:

2015-09-22 10:50:32.067 MutableArrayDemo[90943:3898163] {
    age = 23;
    name = zhangsan;
}
2015-09-22 10:50:32.069 MutableArrayDemo[90943:3898163] zhangsan
2015-09-22 10:50:32.082 MutableArrayDemo[90943:3898163] Plist檔案中的字典:{
    age = 25;
    name = Jack;
}
2015-09-22 10:50:32.082 MutableArrayDemo[90943:3898163] Plist中的年齡:25



github主頁:https://github.com/chenyufeng1991  。歡迎大家訪問!