【问题标题】:__NSCFString objectForKeyedSubscript: exception__NSCFString objectForKeyedSubscript: 异常
【发布时间】:2023-04-07 23:29:02
【问题描述】:

我从服务器获取数据。我的应用程序在 Sinulator 和测试设备 iPhone 4s 上运行良好,但一个人在 iPod 4 上遇到问题。他得到了异常:

-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x1d263a20

我不能使用这个设备,所以我编写代码来了解崩溃的位置。

 if (![dictionaryRest[@"compliments"] isEqual:[NSNull null]]) {
       NSMutableArray *array = [NSMutableArray new];
       NSMutableArray *firstArray = [NSMutableArray new];
       for (NSDictionary *dic in dictionaryRest[@"compliments"]) {
            Compliment *compl = [Compliment new];
            if (![dic[@"ID_promotions"] isEqual:[NSNull null]])
                compl.ID = [dic[@"ID_promotions"] integerValue];

所以在最后 2 个字符串中,这个异常是。这是什么原因?所以我明白我需要使用

if ([dict objectForKey:[@"compliments"])

改为

if (![dict[@"compliments"] isEqual:[NSNull null]])

在所有其他情况下。

我现在进行测试,我的字典中有 ID:

【问题讨论】:

    标签: ios objective-c json nsdictionary


    【解决方案1】:

    您的字典中有一个 NSString 实例,您希望在该实例中有字典。

    请注意,您的“用这个代替那个”与问题无关。

    【讨论】:

    • 所以在我的情况下dic 是字符串?我可以拿 id 对象然后发现它是字典吗?喜欢for (id obj in dictionaryRest[@"compliments"]) if([obj isKindOfClass:[NSDictionary class]]) 如果是字典我继续
    • 也许吧。当你认为它是一个字典而不是编写忽略问题的代码时,你最好回答为什么你有一个字符串。我建议 NSLog(@"dict %@", dictionaryRest); 并确保您确切知道您的数据是怎么回事!
    【解决方案2】:

    -objectForKeyedSubscript:是 NSDictionary 对象的实例方法。 __NSCFString objectForKeyedSubscript: 异常表示方法 -objectForKeyedSubscript 以某种方式在某个 NSString 对象上被调用。 所以基本上你只需要正确检查对象的类,然后你就可以安全地假设它实际上是字典。

    if([dic isKindOfClass:[NSDictionary class]]) 
    {
        id obj = dic[@"key"];
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-27
      • 2021-08-14
      • 1970-01-01
      • 2014-07-04
      相关资源
      最近更新 更多