从 plist 读取 bool 值时出现问题
以下代码每次都会记录“NO”。非常感谢您的帮助!
代码:
NSString *filePath = @"settings.plist";
NSDictionary* plistDictionary = [[NSDictionary alloc] initWithContentsOfFile:filePath];
if ([[plistDictionary objectForKey:@"hideToolBarInDetailedView"] boolValue] == YES) {
detailedView.hidesBottomBarWhenPushed = YES;
NSLog(@"YES");
} else {
detailedView.hidesBottomBarWhenPushed = NO;
NSLog(@"NO");
}
[plistDictionary release];
settings.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>hideToolBarInDetailedView</key>
<true/>
</dict>
</plist>
The following code logs "NO" every time. Help would be very appreciated!
Code:
NSString *filePath = @"settings.plist";
NSDictionary* plistDictionary = [[NSDictionary alloc] initWithContentsOfFile:filePath];
if ([[plistDictionary objectForKey:@"hideToolBarInDetailedView"] boolValue] == YES) {
detailedView.hidesBottomBarWhenPushed = YES;
NSLog(@"YES");
} else {
detailedView.hidesBottomBarWhenPushed = NO;
NSLog(@"NO");
}
[plistDictionary release];
settings.plist:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>hideToolBarInDetailedView</key>
<true/>
</dict>
</plist>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我怀疑 plist 文件不在当前工作目录中,并且
initWithContentsOfFile:
返回的NSDictionary
为空或为零。您可以通过记录 plistDictionary 来验证这一点:一种解决方案是指定 plist 文件的完整路径。或者,如果 plist 文件中存储的值是首选项,则可以使用 NSUserDefaults。
I suspect the plist file isn't in the current working directory and the
NSDictionary
returned byinitWithContentsOfFile:
is empty or nil. You can verify this by loggingplistDictionary
:One solution would be to specify the full path of the plist file. Or, if the values stored in the plist file are preferences, you could use
NSUserDefaults
.这对我有用。在您的情况下,它可能找不到您的文件,在这种情况下 plistDictionary 将为 nil,这将产生您所看到的输出,请尝试添加一个检查,以确保 init 调用实际上返回了一个字典而不是 nil。
It worked for me. Its possible that in your case its not finding your file, in which case plistDictionary will be nil, and that would produce the output you're seeing, try adding a check that init call actually returned you a dictionary and not nil.
由于 key 的对象也可以是另一个类,所以 boolValue 可能会出错(如果不是 NSNumber 类,则可能会生成异常),如果它是数字 0 或 1,则无论是什么谎言,这都是我的解决方案:
没有例外,并告诉你真相!
Since a object for key can be also another class, boolValue can buggie (can generate an exception if not a NSNumber class) and whatever be lying if it is a number 0 or 1, this is my solution:
No exceptions, and tell you the truth!