如果是可变字典,那么在使用'setObject: forKey:'方法时,如果key使用的是NSNumber类型的key,会导致writeToFile失败.
至于为什么是这样,有待进一步研究,当然,如果有人遇到过并找出原因,也可以回复一下,相互学习,共同进步.
附上当时代码
- (void)saveContactListDict:(id)list {
NSMutableArray *contactListArray = [NSMutableArray array];
for (NSDictionary *dict in list) {
for (NSString *key in dict) {
if ([dict[key] isKindOfClass:[NSArray class]]) {
[contactListArray addObjectsFromArray:dict[key]];
}
}
}
NSMutableDictionary *userNameDict = [NSMutableDictionary dictionary];
NSMutableDictionary *avatarurlDict = [NSMutableDictionary dictionary];
NSMutableDictionary *avatarurlAndNameDict = [NSMutableDictionary dictionary];
for (NSDictionary *dict in contactListArray) {
if (dict[@"userId"] == nil) {
return;
}
[userNameDict setObject:dict[@"userName"] forKey:dict[@"userId"]];
NSString *url =dict[@"avatarUrl"];
NSString *avatarUrl = [CPUtil getThumUrl:url size:CGSizeMake(200, 200)];
[avatarurlDict setObject:avatarUrl forKey:dict[@"userId"]];
if (dict[@"userName"] == nil) {
return;
}
[avatarurlAndNameDict setObject:avatarUrl forKey:dict[@"userName"]];
}
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString *userNameDictPath = [path stringByAppendingPathComponent:@"userNameDict.plist"];
NSString *avatarurlDictPath = [path stringByAppendingPathComponent:@"avatarurlDict.plist"];
NSString *avatarurlAndNameDictPath = [path stringByAppendingPathComponent:@"avatarurlAndNameDict.plist"];
[userNameDict writeToFile:userNameDictPath atomically:YES];
[avatarurlDict writeToFile:avatarurlDictPath atomically:YES];
[avatarurlAndNameDict writeToFile:avatarurlAndNameDictPath atomically:YES];
}
分析问题
实际开发当中,总是有细节的东西,虽然有时候觉得,这些东西太基础,但是就在这些基础的知识上,我们却忽略了一些本应该注意的点.好比说我们明明知道向数组中添加元素的时候,元素不能为空,记得考虑为nil,null的情况.这谁都知道,但是却最容易被忽略,因为你无法确定后台的数据返回什么,包括那些规范文档明确要求不能为nil的字段,都有可能返回一个nil or Null .这个时候开始想静静了.明白这个世界其实没有必然的东西.另外,数组越界问题也一直都在,当然为了防止App直接闪退,你可以选择去覆盖系统的方法......好了,言归正传.我们看一下苹果官方文档,回顾一下基础的东西,文档中关于NSDictionary和writeToFile有下面两段内容
NSDictionary
*A key-value pair within a dictionary is called an entry. Each entry consists of one object that represents the key and a second object that is that key's value. Within a dictionary, the keys are unique. That is, no two keys in a single dictionary are equal (as determined by isEqual(_:)). In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see Accessing Object Properties). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull.*










