8th,March,2016 Tuesday
简述
数组是有序的,字典集合是无序的。
"In general, a key can be any object (provided that it conforms to theNSCopying protocol—see below), but note that when using key-value coding the key must be a string (seeKey-Value Coding Fundamentals). Neither a key nor a value can benil; if you need to represent a null value in a dictionary, you should useNSNull"--from apple
大体上,键可以是遵循NSCoping协议的任意对象,但大多数情况是string。 键与值都不可以是nil,如果想显示一个空值,应使用NSNull。
1. 初始化
1)
NSDictionary *dic = @{@"name":@"jolieyang",@"age":23,@"gender":@"woman"};
2)
<span style="color: rgb(63, 63, 63);">NSDictionary *dictionary = [[NSDictionary alloc] </span><span style="color:#993399;">initWithObjectsAndKeys</span><span style="color:#3f3f3f;">:
@"name",@"jolieyang",@"age",@"23",@"gender",@"woman", nil];</span>
3)
//遍历构造器方法
<span style="color: rgb(63, 63, 63);"> NSDictionary *dictionary1 = [NSDictionary </span><span style="color:#993399;">dictionaryWithObjectsAndKeys</span><span style="color:#3f3f3f;">:
@"jolieyang",@"name",@"23",@"age",@"woman",@"gender",nil];</span>
4)
+ (NSDictionary<KeyType,ObjectType> *)dictionaryWithContentsOfFile:(NSString *)path;
// path A full or relative pathname. The file identified by path must contain a string representation of a property list whose root object is a dictionary.
eg:
<span style="color:#3f3f3f;"> NSURL *url = [NSURL URLWithString:@"file:///Users/jolie/Downloads/CodeResources.plist"];// 文件完整路径</span><p class="p1"><span class="s1" style="color: rgb(63, 63, 63);">NSDictionary</span><span class="s2" style="color: rgb(63, 63, 63);"> *dict = [</span><span class="s1" style="color: rgb(63, 63, 63);">NSDictionary</span><span class="s2" style="color: rgb(63, 63, 63);"> </span><span class="s3"><span style="color:#993399;">dictionaryWithContentsOfURL</span></span><span class="s2"><span style="color:#993399;">:url</span><span style="color:#3f3f3f;">];</span></span></p>
5)
+ (NSDictionary<KeyType,ObjectType> *)dictionaryWithContentsOfURL:(NSURL *)aURL;
// aURL An URL that identifies a resource containing a string representation of a property list whose root object is a dictionary.
<span style="color: rgb(63, 63, 63);"> NSDictionary *dictionary1 = [NSDictionary </span><span style="color:#993399;">dictionaryWithContentsOfFile</span><span style="color:#3f3f3f;">:@"/Users/jolie/Downloads/CodeResources"];</span>
2.遍历字典
1)获取所有的keys和values
allKeys allValues
2) 遍历
for(NSString *str in [tmpDict allKeys])
3. 添加元素
[tmpDict setObject:@"jolieYang" forKey:@"name"]
4. 删除元素
1) 按key删除
[tmpDict removeObjectFromKey:@"name"];
2) 删除所有元素
[tmpDict removeAllObjects];
未完待续。。。敬请期待
参考资料:
【学习ios之路:Object-C】字典.集合.