我现在感到很茫然,我似乎无法弄清楚为什么我的简单if / else语句会破坏我的for循环。这两种方法可以保存和读取plist中的数据。评论文本被评论时,一切正常。取消注释后,数据无法保存(或无法正确读取)。
编辑:更新下面的代码后删除[NSNull null](更新的代码可以在下面看到),我仍然有完全相同的问题。有什么想法吗?
此外," tab"是一个NSMutableArray。
- (void)saveDataToFile
{
// translate objects in to an nsarray that contains dictionaries so we can write
NSMutableArray *a = [NSMutableArray array];
for (int c = 0; c < [self.employeeList count]; c++) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
id r = [self.employeeList objectAtIndex:c];
[dictionary setObject:[r username] forKey:@"username"];
[dictionary setObject:[r passWord] forKey:@"passWord"];
[dictionary setObject:[r employeeName] forKey:@"employeeName"];
[dictionary setObject:[r email] forKey:@"email"];
[dictionary setObject:[r phone] forKey:@"phone"];
[dictionary setObject:[r hours] forKey:@"hours"];
// if ([r tab] != nil) {
// [dictionary setObject:[r tab] forKey:@"tab"];
// }
[dictionary setValue:[NSNumber numberWithFloat:[r tabTotal]] forKey:@"tabTotal"];
[a addObject:dictionary];
}
[a writeToFile:[self dataFileName] atomically:YES];
}
- (void)readDataFromFile
{
[self createEmployeeList];
NSArray *tempArray = [NSArray arrayWithContentsOfFile:[self dataFileName]];
for (int d = 0; d < [tempArray count]; d++) {
Employee *person = [[Employee alloc] init];
NSDictionary *dict = [tempArray objectAtIndex:d];
[person setUsername:[dict objectForKey:@"username"]];
[person setPassWord:[dict objectForKey:@"passWord"]];
[person setEmployeeName:[dict objectForKey:@"employeeName"]];
[person setEmail:[dict objectForKey:@"email"]];
[person setPhone:[dict objectForKey:@"phone"]];
[person setHours:[dict objectForKey:@"hours"]];
// if ([dict objectForKey:@"tab"] == nil) {
// NSMutableArray *array = [[NSMutableArray alloc] init];
// [person setTab:array];
// }else {
// [person setTab:[dict objectForKey:@"tab"]];
// }
[person setTabTotal:[[dict valueForKey:@"tabTotal"] floatValue]];
[self.employeeList addObject:person];
}
}
答案 0 :(得分:1)
您无法将NSNull值保存到字典文件中。你只能拥有一组有限的类型,比如NSString,NSNumber,NSArray,NSDictionary。
保存时,不要将值设置为NSNull,也不要设置它。
阅读时,如果objectForKey:
返回nil,则表示没有设置此类密钥。
如果确实想要存储NSNull值,请看一下:How to serialize a NSDictionary/NSArray/Property List (plist) which contains NSNull。