从 plist 读取 bool 值时出现问题

发布于 2024-10-03 05:25:05 字数 805 浏览 4 评论 0原文

以下代码每次都会记录“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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

又爬满兰若 2024-10-10 05:25:05

我怀疑 plist 文件不在当前工作目录中,并且 initWithContentsOfFile: 返回的 NSDictionary 为空或为零。您可以通过记录 plistDictionary 来验证这一点:

NSLog(@"%@", plistDictionary);

一种解决方案是指定 plist 文件的完整路径。或者,如果 plist 文件中存储的值是首选项,则可以使用 NSUserDefaults。

I suspect the plist file isn't in the current working directory and the NSDictionary returned by initWithContentsOfFile: is empty or nil. You can verify this by logging plistDictionary:

NSLog(@"%@", plistDictionary);

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.

若言繁花未落 2024-10-10 05:25:05

这对我有用。在您的情况下,它可能找不到您的文件,在这种情况下 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.

深爱成瘾 2024-10-10 05:25:05

由于 key 的对象也可以是另一个类,所以 boolValue 可能会出错(如果不是 NSNumber 类,则可能会生成异常),如果它是数字 0 或 1,则无论是什么谎言,这都是我的解决方案:

- (BOOL)isBooleanKey:(id)key
{
#ifndef kNullString // can be somewhere
#define kNullString @"(null)"
#endif
    if (!key){
        NSLog(@"WARNING:[- (BOOL)%@(id)key, \"key\" is nil]\n", NSStringFromSelector(_cmd));
        return NO;
    }
    if ([key isKindOfClass:[NSNumber class]]) {
        NSDictionary *dict = [NSDictionary dictionaryWithObject:key forKey:@"test"];

        if (!dict) return NO;

        NSError *err = nil;
        NSPropertyListFormat fmt = NSPropertyListXMLFormat_v1_0;

        id data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:&err];
        if(!data) {
            NSLog(@"dict is not a XMLFormat v1\n"); // anyway this can't be happen here, unless something is really bad!
        }

        id pl =[NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:&fmt error:&err];
#if 0
        NSLog(@" err: %@", err.localizedDescription);
#endif
        if(!pl) {
            [NSException raise: NSParseErrorException format:@"%@\n", err];
            if(![data isKindOfClass:[NSDictionary class]])
                [NSException raise: NSParseErrorException
                            format: @"dict does not contain a property list\n"];
        }
        NSString* plist = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (plist.length < 1 || [plist isEqualToString:kNullString]) return NO; //kNullString is a macro -> @"(null)"

        // dict has only one key, so if it's not soup is soaked bread!
        if ([plist rangeOfString:@"<true/>"].location != NSNotFound
            || [plist rangeOfString:@"<false/>"].location != NSNotFound) {
            // object for key is a boolean for sure (not simply a number!)
            return YES;
        }
    }
    // key is not a boolean
    return NO;
}

没有例外,并告诉你真相!

if ([self isBooleanKey:[someobject forKey:@"some key"]]]) {
   // Yes
} else {
   // NO
}

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:

- (BOOL)isBooleanKey:(id)key
{
#ifndef kNullString // can be somewhere
#define kNullString @"(null)"
#endif
    if (!key){
        NSLog(@"WARNING:[- (BOOL)%@(id)key, \"key\" is nil]\n", NSStringFromSelector(_cmd));
        return NO;
    }
    if ([key isKindOfClass:[NSNumber class]]) {
        NSDictionary *dict = [NSDictionary dictionaryWithObject:key forKey:@"test"];

        if (!dict) return NO;

        NSError *err = nil;
        NSPropertyListFormat fmt = NSPropertyListXMLFormat_v1_0;

        id data = [NSPropertyListSerialization dataWithPropertyList:dict format:NSPropertyListXMLFormat_v1_0 options:0 error:&err];
        if(!data) {
            NSLog(@"dict is not a XMLFormat v1\n"); // anyway this can't be happen here, unless something is really bad!
        }

        id pl =[NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainersAndLeaves format:&fmt error:&err];
#if 0
        NSLog(@" err: %@", err.localizedDescription);
#endif
        if(!pl) {
            [NSException raise: NSParseErrorException format:@"%@\n", err];
            if(![data isKindOfClass:[NSDictionary class]])
                [NSException raise: NSParseErrorException
                            format: @"dict does not contain a property list\n"];
        }
        NSString* plist = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        if (plist.length < 1 || [plist isEqualToString:kNullString]) return NO; //kNullString is a macro -> @"(null)"

        // dict has only one key, so if it's not soup is soaked bread!
        if ([plist rangeOfString:@"<true/>"].location != NSNotFound
            || [plist rangeOfString:@"<false/>"].location != NSNotFound) {
            // object for key is a boolean for sure (not simply a number!)
            return YES;
        }
    }
    // key is not a boolean
    return NO;
}

No exceptions, and tell you the truth!

if ([self isBooleanKey:[someobject forKey:@"some key"]]]) {
   // Yes
} else {
   // NO
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文