首页 > 白话Objective-C > 白话Objective-C之NSDictionary

白话Objective-C之NSDictionary

NSDictionary是一个非常重要的集合类,类似于hash表。

NSDictionary一些常用用法的示例:

//创建,以nil为结束标志
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"Object1",@"key1",@"Object2",@"key2",nil];
//遍历
for(NSString *key in dictionary)
{
    NSLog(@"key=%@,Object=%@",key,[dictionary objectForKey:key]);
}

//查询key的值
NSLog(@"objectForKey key1 = %@",[dictionary objectForKey:@"key1"]);

//得到key-value的个数
NSInteger count = [dictionary count];
NSLog(@"count = %lu",count);

//得到所有key
NSArray *keys = [dictionary allKeys];
NSLog(@"keys = %@",keys);

//得到所有value
NSArray *values = [dictionary allValues];
NSLog(@"values = %@",values);

//将Setting.plist的内容读取到dictionary里面
NSString * plist = [[NSBundle mainBundle] pathForResource:@"Setting" ofType:@"plist"];
BOOL success = [dictionary writeToFile:plist atomically:YES];

//将dictionary里面的内容写入到Setting.plist里面
dictionary =[NSDictionary dictionaryWithContentsOfFile:plist];

(转载本站文章请注明出处 www.helloitworks.com ,请勿用于任何商业用途)

  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.