How can I add a boolean value to a NSDictionary?

后端 未结 5 1746
长情又很酷
长情又很酷 2021-01-30 05:46

Well, for integers I would use NSNumber. But YES and NO aren\'t objects, I guess. A.f.a.i.k. I can only add objects to an NSDictionary, right?

5条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 06:40

    Try this:

    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:[NSNumber numberWithBool:TRUE]  forKey:@"Pratik"];
    [dic setObject:[NSNumber numberWithBool:FALSE] forKey:@"Sachin"];
    
    if ([dic[@"Pratik"] boolValue])
    {
        NSLog(@"Boolean is TRUE for 'Pratik'");
    }
    else
    {
        NSLog(@"Boolean is FALSE for 'Pratik'");
    }
    
    if ([dic[@"Sachin"] boolValue])
    {
        NSLog(@"Boolean is TRUE for 'Sachin'");
    }
    else
    {
        NSLog(@"Boolean is FALSE for 'Sachin'");
    }
    

    The output will be as following:

    Boolean is TRUE for 'Pratik'

    Boolean is FALSE for 'Sachin'

提交回复
热议问题