2013-10-24 82 views
2

我有来自服务器的JSON响应,并且存在格式1 = true,0 = false的bool变量。无法处理@“1”

在我的代码我这样做:

我第一次尝试:

NSString *bolean=[dict objectForKey:@"featured"]; 
    if ([bolean isEqualToString:@"1"]) // here application fails... 
    { 
     BOOL *a=[bolean boolValue]; 
     [newPasaka setFeatured:a]; 
    } 
    else 
    { 
     BOOL *a=[bolean boolValue]; 
     [newPasaka setFeatured:a]; 
    } 

我的第二次尝试:

这认为1 = NO,0 = NULL

NSString *bolean=[dict objectForKey:@"featured"]; 
    if ([bolean boolValue]) //if true (1) 
    { 
     BOOL *a=[bolean boolValue]; 
     [newPasaka setFeatured:a]; 
    } 
    else //if false (0) 
    { 
     BOOL *a=[bolean boolValue]; 
     [newPasaka setFeatured:a]; 
    } 

如何解决此问题?

而我的班级也处理这个疯狂..当我设置功能到YES - 它设置NO。当我设置NO - 它集null.

这里是我的类:

* .h

@property BOOL *featured; 

* .m

@synthesize featured; 
+0

我想这是唯一的例子代码,但我喜欢看这样的东西'如果(测试){DoSomething的; } else {doSomething; }' – Cyrille

+0

这是非常奇怪的使用指针BOOL – HereTrix

回答

4

更改此财产 -

@property BOOL *featured; 

TO

@property (assign) BOOL featured; 

BOOL是基本数据类型,并且不能被直接创建为一个对象。但是,如果您需要将其用作对象,请将其包装在基础类中,如NSNumberNSString。这样的 -

NSNumber *featuredObject = [NSNumber numberWithBool:featured]; 

,并取回这样的价值 -

BOOL featured = [featuredObject boolValue]; 

困惑布尔VS BOOL?阅读here

+0

虽然这是正确的,请解释_why_这是解决方案(以及代码中的'BOOL * a'也需要更改)。 – DarkDust

+0

@Dharmbir Choudhary:你的编辑不正确。请回复它。 – DarkDust

+0

@DarkDust对不起,我错了。 –

3

BOOL是不是一类,是

BOOL a = [bolean boolValue]; 

BOOL *a = [bolean boolValue]; // this is wront 
使用JSON

反正该值应rapresented为数字,而不是字符串,除非API你正在处理原始类型与,强制该值是一个字符串。把一个断点在objectForKey后在控制台打印类“bolean”的对象:

po [bolean class] 

所以你肯定你正在处理的对象的类型,然后在一些情况下(如应该是)只使用[布尔boolValue]

0

BOOL是原始类型,所以你不需要使用指针。

更改此属性从

@property BOOL *featured; 

@property BOOL featured; 

然后,你需要替换此代码:

NSString *bolean=[dict objectForKey:@"featured"]; 
    if ([bolean isEqualToString:@"1"]) // here application fails... 
    { 
     BOOL *a=[bolean boolValue]; 
     [newPasaka setFeatured:a]; 
    } 
    else 
    { 
     BOOL *a=[bolean boolValue]; 
     [newPasaka setFeatured:a]; 
    } 

与此:

NSString *bolean=[dict objectForKey:@"featured"]; 
[newPasaka setFeatured:[boolean boolValue]] 

它大大简化和工程罚款

0

你可以做另一种方式是已经修改如下: -

@property (assign) Bool featured; 
NSString *bolean=[dict objectForKey:@"featured"]; 
Bool yourBoolValue=[bolean boolValue]; 
    if (yourBoolValue==1]) // here if (true) 
    { 
     Bool a=yourBoolValue; 
     [newPasaka setFeatured:a]; 
    } 
    else//if (false) 
    { 
     Bool a=yourBoolValue; 
     [newPasaka setFeatured:a]; 
    } 
+0

'Bool'在Objective-C中不是有效的类型。无论是“bool”还是“BOOL”。此外,你不检查'1',而是检查'YES'或者'true'(或者根本不检查,因为'if(yourBoolValue)'就足够了)。 – DarkDust

+0

@DarkDust,谢谢:)纠正我没有注意到 –

0

假设dict是反序列化JSON对象,并且布尔值表示为JSON数量(0或1),那么你得到一个布尔值如下:

BOOL isFeatured = [dict[@"featured"] boolValue]; 

或者你的代码可以写为:

[newPasaka setFeatured:[dict[@"featured"] boolValue]]; 

或利用阿肖克的更正财产申报:

newPaska.featured = [dict[@"featured"] boolValue]; 

;)