从具有BOOL值的plist问题中读取NSDictionary

时间:2011-10-06 19:56:18

标签: iphone objective-c ipad nsdictionary

所以我有以下方法:

- (void)readPlist
{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];    
    self.data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

    BOOL value = (BOOL)[self.data valueForKey:@"Arizona"];
    NSLog(@"VALUE IS %d", value);

}

它读取plist很好,它可以检测到它有7个键,但是当我尝试打印出来的值时,如果它是no,则给出32,如果是,则给出24。我做错了什么?

3 个答案:

答案 0 :(得分:23)

valueForKey返回一个id。这样做:

NSNumber * n = [self.data valueForKey:@"Arizona"];
BOOL value = [n boolValue];

答案 1 :(得分:1)

- (void)readPlist
{

NSString *path = [[NSBundle mainBundle] pathForResource:@"States" ofType:@"plist"];    
self.data = [[NSMutableDictionary alloc] initWithContentsOfFile:path];

BOOL value = [[self.data valueForKey:@"Arizona"] intValue];
NSLog(@"VALUE IS %i", value);

}

答案 2 :(得分:0)

以为我会参与其中。首先,如何在plist中定义BOOL值?

Apple's DTD for plist提供了一个不错的线索:

<!ENTITY % plistObject "(array | data | date | dict | real | integer | string | true | false )" >

以后:

<!-- Numerical primitives -->
<!ELEMENT true EMPTY>  <!-- Boolean constant true -->
<!ELEMENT false EMPTY> <!-- Boolean constant false -->

一切都很好,但是在plist中看起来怎么样?

嗯,对于真正的价值,它将是:

    <dict>
        <key>employeeId</key>
        <integer>1</integer>
        <key>name</key>
        <string>Joe Smith</string>
        <key>worksRemotely</key>
        <true/>
    </dict>

当然是假的:

    <dict>
        <key>employeeId</key>
        <integer>1</integer>
        <key>name</key>
        <string>Joe Smith</string>
        <key>worksRemotely</key>
        <false/>
    </dict>

要从plist创建一个对象,作为Objectify的敏锐用户,我从他们的工厂类中获取灵感。我的Employee课程会有以下方法:

+ (Employee *)instanceFromDictionary:(NSDictionary *)aDictionary {

    Employee *instance = [[Employee alloc] init];

    [instance setAttributesFromDictionary:aDictionary];
    return instance;
}

反过来调用:

- (void)setAttributesFromDictionary:(NSDictionary *)aDictionary {

    if (![aDictionary isKindOfClass:[NSDictionary class]]) {
        return;
    }

    [self setValuesForKeysWithDictionary:aDictionary];

}

setValuesForKeysWithDictionary:aDictionaryNSKeyValueCoding Protocol的成员。每个NSObject都可以使用,这意味着NSObject的子类,我们的Employee类可以免费获得。

只要我的Employee类'属性与plist中指定的键值匹配,即employeeIdnameworksRemotely,那么我就不需要做任何事情了其他。该方法将plist中指定的worksRemotely布尔值转换为类实例中的正确值:

@property (assign, nonatomic, getter = isWorkingRemotely) BOOL worksRemotely;

剩下的就是遍历plist内容,创建我想要的类的实例,包括bool:

NSString *plistPath = [[NSBundle bundleForClass:[self class]] pathForResource:@"employees" ofType:@"plist"];
NSArray *employeeDictionaries = [NSArray arrayWithContentsOfFile:plistPath];
for (NSDictionary *employeeDict in employeeDictionaries) {
     Employee *employee = [Employee instanceFromDictionary:employeeDict];
     [employees addObject:employee];
}

毫无疑问,在回答具体问题时,我已经有点过头了。然而,希望这对于在试图做我正在尝试的事情时偶然发现这个问题的其他人来说是有用的,即在plist中创建一个具有布尔值的类。