【问题标题】:Incompatible pointer to integer conversion returning 'id _Nullable' from a function with result type 'NSInteger' (aka 'long')从结果类型为“NSInteger”(又名“long”)的函数返回“id _Nullable”的整数转换指针不兼容
【发布时间】:2021-09-10 12:11:09
【问题描述】:

我想要一个对象来保存数组的索引,其中 id 是唯一键,它的值是索引 ({[id]:[index]})

我想动态返回该索引,即在 javascript 中我会做这样的事情

const a = [{
  id: '451', 
  name: 'varun'
}]


const b = {
    '451': 0 
}

const c = '451' 

if (b[c]) return b[c] 
else return -1 

它在 obj c 中的等价物是什么?

目前我正在这样做

@implementation Participants {
    NSMutableDictionary *participantsKey;
}. // Equivalent to const b above


- (NSInteger)doesParticipantExist:(NSString*)id {
    if ([participantsKey valueForKey: id]) {
      return [participantsKey valueForKey: id];
    } else {
      return -1;
    }
  }

但这会引发以下警告

从结果类型为“NSInteger”(又名“long”)的函数返回“id _Nullable”的整数转换指针不兼容

【问题讨论】:

    标签: javascript ios objective-c xcode


    【解决方案1】:

    valueForKey 返回一个可为空的对象 'id _Nullable' 而不是 NSInteger 这是一个 long 值。

    [participantsKey valueForKey: id]
    

    您的函数的返回类型是NSInteger,这就是为什么它说它不能将可空对象'id _Nullable' 转换为NSInteger

    您可以采取以下措施来解决此问题。

    - (NSInteger)doesParticipantExist:(NSString*)id {
        if ([participantsKey valueForKey:id]) {
            // Fix here
            return [(NSNumber*)[participantsKey valueForKey:id] integerValue];
        } else {
            return -1;
        }
    }
    

    【讨论】:

    • 感谢您回答这个问题并帮助我解决之前的问题 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多