ios id 不转换为 nsinteger

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

我有以下从 block 返回的响应:

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]);
        }

我做错了什么?

最佳答案

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];

关于ios id 不转换为 nsinteger,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27532700/

相关文章:

ios - 添加到 AppDelegate 时找不到 Google/Analytics.h 文件

ios - Swift 如何修复 Target Membership 的错误?

ios - iOS:xCode无法识别新的类方法

ios - 如何找到 NSMutableArray 的最小和最大对象

ios - 第二次使用一个方法给我一个错误(IOS)

objective-c - 在 UITableView 中加载本地 json 信息

iphone - 在 NSDictionary 中存储/提取对象

ios - 通过键从 NSMutableArray 中删除对象

ios - 为什么在 iOS 7 中我的本地通知没有显示横幅

objective-c - NSNumber 的 @property 属性?