❤简介:
1.NSDictionary为字典,也是用来存储元素的,里面每一个元素都是以键值对的形式存在
2.键值一一对应,通过一个键找到一个值
3.键不可重复,值可以
1.一个元素的创建
//
创建一个元素的字典
(
键值对
)
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"100" forKey:@"Score"];
NSLog
(
@"%@"
,dict );
输出结果
:Score =
100
;
2.多个元素的创建
//
字典多个元素的创建
NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"3",@"a",@"4",@"b", nil];
NSLog(@"%@",dict1);
输出结果
:a = 3,b = 4;
3.简便方法(快速建立)
1.
//
快速建立
格式
@{}
大括号
NSDictionary *dict3 =@{@"a":@"3",@"b":@"4"};
NSLog
(
@"%@"
,dict3);
输出结果
:a =
3
;b =
4
;
2.求值
NSString
*str = dict3[@“a"]
NSLog
(
@“a = %@“,str
);
输出结果:a = 3;
4.字典的遍历
1.用法:forin增强for循环 --- NSString * obj = [dict3 objectForKey:key];
—等同于 NSString
* obj = dict3[key]; (
简便写法
)
NSDictionary
*dict3 =
@{
@"a"
:
@"3"
,
@"b"
:
@"4"
}
;
//
增强
for
循环遍历字典
取得
(key)
键
for
(
NSString
*key
in
dict3) {
//
取得
key
键
// NSLog(@"%@",key);
//
通过
key
键,获得值
NSString * obj = [dict3 objectForKey:key]; 第一种方法
NSString
* obj = dict3[key]; 第二种方法
NSLog
(
@"key = %@,obj = %@"
,key,obj);
输出结果: key = a,obj = 3 ; key = b,obj = 4
输出结果: key = a,obj = 3 ; key = b,obj = 4
2.block遍历
NSDictionary
*dict3 =
@{
@"a"
:
@"3"
,
@"b"
:
@"4"
}
;
[dict3
enumerateKeysAndObjectsUsingBlock
:^(
id
_Nonnull
key,
id
_Nonnull
obj,
BOOL
*
_Nonnull
stop) {
NSLog(@"key = %@,obj = %@",key,obj);
}];
5.字典的读写文件与数组一样
6.可变字典
详解:
//
可变空字典的创建
NSMutableDictionary
*dict = [
NSMutableDictionary
dictionary
];
// 添加元素 值 键
[dict setObject : @"yaya" forKey : @"a” ]; 1
NSLog ( @"%@" ,dict);
// 输出结果: a = yaya;
// 添加元素 值 键
[dict setObject : @"yaya" forKey : @"a” ]; 1
NSLog ( @"%@" ,dict);
// 输出结果: a = yaya;
//
删除元素
--
通过
key
删除
value
[dict removeObjectForKey:@"a"];
NSLog
(
@"%@"
,dict);
// 输出结果:
// 清空 - 删除所有键值对
[dict removeAllObjects ];
// 简便方法
dict[ @"ww" ] = @"3” ; 2
NSLog ( @"%@" ,dict);
// 输出结果:
// 清空 - 删除所有键值对
[dict removeAllObjects ];
// 简便方法
dict[ @"ww" ] = @"3” ; 2
NSLog ( @"%@" ,dict);
//
输出结果:
ww = 3;
注:1等同于2
7.补充NSURL
详解:
//
路径
NSURL
*url = [
NSURL
URLWithString
:
@"file:///Users/mac/Desktop/1.txt/"
];
NSString
*str =
@"
你好,世界!
"
;
// 将 str 写入 url 布尔类型
BOOL result = [str writeToURL :url atomically : YES encoding : NSUTF8StringEncoding error : nil ];
// 将 str 写入 url 布尔类型
BOOL result = [str writeToURL :url atomically : YES encoding : NSUTF8StringEncoding error : nil ];
if (result) {
NSLog(@"
写入成功
");}
else {NSLog(@"
写入失败
"
);}