ios id不会转换为nsinteger

时间:2014-12-17 18:50:04

标签: ios objective-c nsdictionary objective-c-blocks

我从块中返回以下响应:

response: {
    error = "";
    success = 1;
}

我尝试评估“成功”,但它从未评估为仅等于1作为“其他”:

NSLog(@"response: %@", responseObject);
        NSInteger success = (NSInteger)responseObject[@"success"];
        NSString *errorMessage = (NSString *)responseObject[@"error"];
        if (success == 0) {
            NSLog(@"success is false");
            NSLog(@"JSON: %@", errorMessage);


            saveCallback(NO, [self createErrorFromDescription:errorMessage]);
        }else if (success == 1){
            NSLog(@"success is true");
            saveCallback(YES, nil);
        }else{
            NSLog(@"success is else");
            NSLog(@"JSON: %@", errorMessage);

            saveCallback(NO, [self createErrorFromDescription:errorMessage]);
        }

我做错了什么?

3 个答案:

答案 0 :(得分:3)

NSInteger是一个原语,id是一个对象(实际上是指向对象的指针),在这种情况下可能是NSNumber

直接将指针强制转换为对象,NSInteger将将其转换为整数值类型,它只会将指针内存重新解释为整数。

要将数字对象转换为整数值,您可以在其上调用integerValue

(也可能是响应中缺少该数字,或者它可以作为NSNull对象返回,因此下面的错误检查)

NSNumber *successNumber = responseObject[@"success"];
NSInteger success;
if (!successNumber || successNumber == [NSNull null]) {
    // the response doesn't contain anything for the "success" key :(
}
// if successNumber is nil, this will be 0. 
// if successNumber is the NSNull object, this will crash (unrecognized selector)
// Just be aware of both of those.
success = [successNumber integerValue];

答案 1 :(得分:1)

NSInteger success = [responseObject[@"success"] integerValue];

答案 2 :(得分:1)

鉴于您似乎正在使用原始json,您需要非常小心,不要使用NULL值;这将导致异常。

由于Objective C中有许多类型的Null,因此最好使用类内省来确保对象有效。

NSDictionary *responseArray = responseObject;
NSInteger success=0;

if([responseObject isKindOfClass:[NSDictionary class]])
{
    // responseObject is safe to subscript
    NSNumber *successNumber = responseObject[@"success"];

    // Use introspection; messaging nil doesn't cause an exception and returns nil
    if ([successNumber isKindOfClass:[NSNumber class]]) 
    {
        // NSInteger is a primitive
        success = [successNumber integerValue];
    }
}

// If success is anything but zero, assume it's true
if (success)
{
    NSLog(@"success is true");
}
else
{
    NSLog(@"success is false");
}

据推测,您的成功键是1或0,因此您可以稍微简化此代码。但总的来说,这就是你要处理的对象可能是NULL而不是简单的nil。

相关问题